Amazon Affiliate

Thursday 31 May 2012

IMPLEMENTATION OF THE STACK USING ARRAYS

// IMPLEMENTATION OF THE STACK USING ARRAYS


 # include<iostream.h>
 # include<stdio.h>
 # include<string.h>
 # include<ctype.h>

 # define size  100

    int top = -1;
    int flag = 0;

    class stacks
     {
       private: int stack[100];
            int data;

       public:
           void push(int *, int);
           int pop(int *);
           void display(int *);
      };

// Definition of the push function

    void stacks :: push(int s[], int d)
         {
          if(top ==(size-1))
         flag = 0;
         else
         {
         flag = 1;
         ++top;
         s[top] = d;

         }
         }

// Definition of the pop function

    int stacks :: pop(int s[])
         {
           int popped_element;
          if(top == -1)
             {
            popped_element = 0;
            flag = 0;
             }
          else
           {
             flag = 1;
             popped_element = s[top];
             --top;
           }
           return (popped_element);
        }

// Definition of the display function

    void stacks :: display(int s[])
        {
           if(top == -1)
          {
            cout<<"Stack is empty";
          }
           else
         {
           for(int i = top; i>=0; --i)
           cout<<"  "<<s[i];
         }
          }

          void main()
           {
         stacks s;
         int stack[size];
         int  data;
         char choice;
         int q = 0;
         int top = -1;

         do
           {
             cout<<" \nPush->i Pop->p Quit->q:";
             cout<<"\nInput the choice : ";
              do
              {
            cin>>choice;
            choice =tolower(choice);
               }while(strchr("ipq",choice)==NULL);
            cout<<"Your choice is ->"<<choice;

      switch(choice)
       {
     case 'i' :
           cout<<"\n Input the element to pushed:";
           cin>>data;
           s.push(stack,data);
           if(flag)
           {
           cout<<"\n After inserting ";
           s.display(stack);
           if(top == (size-1))
            cout<<"\n Stack is full";
           }
           else
           cout<<"\n Stack overflow after pushing";
           break;

    case 'p' : data = s.pop(stack);
          if(flag)
            {
              cout<<"\n Data is popped:"<<data;
              cout<<"\n Rest data in stack is as follows:\n";

              s.display(stack);
            }
            else
            cout<<"\n Stack underflow";
            break;
    case 'q': q = 1;
      }
    } while(!q);
   }

No comments:

Post a Comment