Sunday, 25 September 2011

Stack data structure program

Implementation of stack using Arrays:

//stack program
template<class T>
class stack
{
 private:
  T *s;
  int top,size;
 public:
  void push(T x);
  T pop();
  stack(int k=40);
  ~stack();
  int isfull();
  int isempty();
  void display();
  T topmost();
 };
 template<class T>
stack<T>::stack(int k)
{
 top=-1;
 size=k;
 s=new T[size];
}
//isempty()
template<class T>
int stack<T>::isempty()
{
 return(top==-1);
}
//isfully
template<class T>
int stack<T>::isfull()
{
 return(top==size-1);
}
template<class T>
void stack<T>::push(T x)
{
 if(isfull())
 {
  cout<<"stack is full,Insertion is not possible\n";
 }
 else
 {
  top++;
  s[top]=x;
 }
}
//pop()
template<class T>
T stack<T>::pop()
{
 T x;
 if(isempty())
  return(-1);
 else
 {
  x=s[top];
  top--;
  return(x);
 }
}
template<class T>
void stack<T>::display()
{
 if(isempty())
  cout<<"stack is empty\n";
 else
 {
  cout<<"stack is as follows\n";
  for(int i=top;i>=0;i--)
   cout<<s[i]<<"\n";
 }
}
template<class T>
T stack<T>::topmost()
{
 if(isempty())
  return(-1);
 else
  return(s[top]);
}
void menu1()
{
 cout<<"1. integer stack\n";
 cout<<"2. float stack\n";
 cout<<"3. character stack\n";
 cout<<"4. exit\n";
}
void menu2()
{
 cout<<"1. insertion\n";
 cout<<"2. deletion\n";
 cout<<"3. display\n";
 cout<<"4. topmost value in the stack\n";
 cout<<"5. exit\n";
}
void main()
{
 int ch,k;
 menu1();
 cout<<"enter ur choice\n";
 cin>>ch;
 while(ch<5)
 {
  cout<<"enter size of the stack\n";
  cin>>k;
  case 1:{
        stack<int> a(k);
        operation(a);
        break;
        }
  case 2:{

        stack<float> a(k);
        operation(a);
        break;
        }
case 3:{
        stack<char> a(k);
        operation(a);
        break;
        }
 }
 menu1();
 cout<<"enter ur choice\n";
 cin>>ch;
 }//end of while
}//end of main()
  
      

Stacks
Static implementation of stack

Basic stack operation

No comments:

Post a Comment