Thursday, 14 December 2017

Write a C++ program to implement the Stack ADT using arrays.

Definition of Stack ADT: A stack is an ordered collection of data items into which new items may be inserted and from which data items may be deleted at one end. Stack are also called Last-In-First-out (LIFO) lists.

Basic terminology associated with stacks:
1) Stack Pointer (TOP): Keeps track of the current position the stack.
2) Overflow: Occurs when we try to insert (push) more information on a stack than it can hold.
3) Underflow: Occurs when we try to delete (pop) an item off a stack, which is empty.
Basic Operation Associated with Stacks:
1) Insert (Push) an item into the stack.
2) Delete (Pop) an item from the stack.

Implementation of the above problem using C++:
#include<iostream>
using namespace std;
#define MAX 10
int top=-1,ch,i;
template <class T>
class StackADT
{
public:
virtual void Push()=0;
virtual void Pop()=0;
virtual void Top()=0;
virtual void Display()=0;
};
template <class T>
class Stack: public StackADT<T>
{
T stk[MAX],ele;
public:
void Push();
void Pop();
void Top();
void Display();
};
template <class T>
void Stack<T>::Push()
{
if(top==(MAX-1))
cout<<"\nThe stack is full";
else
{
cout<<"\nEnter an element:";
cin>>ele;
top++;
stk[top]=ele;
cout<<"\nElement pushed successfully\n";
}
}
template <class T>
void Stack<T>::Pop()
{
if(top==-1)
cout<<"\nThe stack is empty";
else
{
ele=stk[top];
top--;
cout<<"The deleted element is:"<<ele;
}
}
template <class T>
void Stack<T>::Top()
{
if(top==-1)
cout<<"\nThe stack is empty";
else
cout<<"The top element of the stack is:"<<stk[top];
}
template<class T>
void Stack<T>::Display()
{
if(top==-1)
cout<<"\nThe stack is empty";
else
{
cout<<"\nThe elements in the stack are:";
for(i=top;i>=0;i--)
cout<<"\n"<<stk[i];
}
}
int main()
{
Stack<int> s1;
do
{
cout<<"\n****MENU****";
cout<<"\n1. Push\n2. Pop\n3. Top\n4. Display\n5. Exit";
cout<<"\nEnter ur Choice:";
cin>>ch;
switch(ch)
{
case 1: s1.Push();
break;
case 2: s1.Pop();
break;
case 3: s1.Top();
break;
case 4: s1.Display();
break;
case 5: exit(1);
default: cout<<"Enter correct Choice";
}
}
while(true);
return 0;
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput