Tuesday, October 19, 2010

Stack in C++

#include <iostream>
        using namespace std;
        #define STACKSIZE 10
        class stack
        {
                private:
                        int arr[STACKSIZE+1];
                        int tos;
                public:
                        stack();
                        void push(int x);
                        int  pop();
                        bool is_empty();
                        bool is_full();
                        int  size();
                        void display();
        };
        stack::stack()
        {
                tos = 0;
        }
        void stack::push(int x)
        {
                if(!is_full())
                        arr[tos++] = x;
                else
                        cout << "Stack is full, Can not push " << x << endl;
        }
        int stack::pop()
        {
                if(!is_empty())
                        return arr[--tos];
                else
                        cout << "Stack is empty, cannot pop" << endl;
                return -1;
        }
        bool stack::is_empty()
        {
                if(tos == 0)
                        return true;
                else
                        return false;
        }
        bool stack::is_full()
        {
                if(tos == STACKSIZE)
                        return true;
                else
                        return false;
        }
        int stack::size()
        {
                return tos;
        }
        void stack::display()
        {
                if(tos == 0)
                {
                        cout << "No elements to display" << endl;
                        return;
                }
                for(int i=0;i
                        cout << arr[i] << " ";
                cout << endl;
        }
        int main()
        {
                stack mystack;
                cout << mystack.size() << endl;
                mystack.push(1);
                if(mystack.is_full())
                        cout << "stack is full" << endl;
                mystack.pop();
                if(mystack.is_empty())
                        cout << "stack is empty" << endl;
        }

No comments:

Post a Comment