Sunday, 2 September 2012

Stack implementation using arrays



#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

class stack
{
private:
    int stack[10],top,max;
public:
    stack()
    {
    top=-1;
    cout<<"stack is created"<<endl;
    cout<<"Enter maximum limit : ";
    cin>>max;
    }
    void menu();
    void push();
    void pop();
    void display();
};

void stack::menu()
{
    int ch;
    do
    {
    cout<<endl;
    cout<<"STACK MENU"<<endl
        <<"1.push"<<endl
        <<"2.pop"<<endl
        <<"3.Display"<<endl
        <<"4.Exit"<<endl;
    cout<<"Enter your choice : ";
    cin>>ch;

    switch(ch)
    {
    case 1: push();
        break;

    case 2: pop();
        break;

    case 3:    display();
        break;

    case 4: exit(0);
        break;

    default:
        cout<<"Sorry! invalid choice"<<endl;

    }
    }while(ch!=4);
}

void stack::push()
{
    int x;
    if(top==(max-1))
       cout<<"stack is overflow"<<endl;
     else
      {
       cout<<"Enter an element: ";
       cin>>x;
       top=top+1;
       stack[top]=x;
      }
}

void stack::pop()
{
    if(top==-1)
       cout<<"stack is underflow"<<endl;
     else
     {
       cout<<"poped element is : "<<stack[top];
       top--;
     }
}

void stack::display()
{
    if(top==-1)
      cout<<"stack is empty"<<endl;
     else
      {
      cout<<"stack elements are : ";
      for(int i=top;i>=0;i--)
          cout<<stack[i]<<" ";
      }
}

void main()
{
   clrscr();
   stack s;
   s.menu();
   getch();
}

No comments:

Post a Comment