Friday, September 23, 2016

Data structures- stack implementation by array

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int Max;
class stack
{
    int *stk,top;
    public:
        stack()
        {
            cout<<"Enter max size for stack\n";
            cin>>Max;
            stk=new int[Max];
            top=0;
        }
        void print()
        {
            if(top==0)
            {
                cout<<"\nStack is empty\n";
            }
            else
            {
                cout<<"\nStack is\n";
              for(int i=top;i>0;i--)
              {
                    cout<<stk[i]<<"\t";
              }
            }
        }
        void push(int item)
        {
            if(top==Max)
            {
                cout<<"\nStack overflow\n";
            }
            top=top+1;
            stk[top]=item;
        }
        int pop()
        {
            if(top==0)
            {
                cout<<"\nStack underflow\n";
                return '\0';
            }
            return stk[top--];
        }
};
int main()
{
    int item;
    class stack s;
    for(int i=0;i<Max;i++)
    {
        cout<<"\nEnter item to be pushed\n";
        cin>>item;
        s.push(item);
    }
    s.print();
    s.pop();
    getch();
    return 0;
}

No comments:

Post a Comment