Skip to main content

Stack in C++

 

#include<bits/stdc++.h>
#define n 5
using namespace std;

class Stack{
    int *a;
    int top;
public:
    Stack(){
         a = new int[n];
         top = -1;
     };
     void push(int x){
            if(top == n -1){
                cout<<"Stack overflow"<<endl;
                return;
            }
            top++;
            a[top]=x;
     }
     void pop(){
         if(top ==-1){
             cout<<"No element in pop"<<endl;
             return;
         }
         top--;
     }
    int Top(){
         if(top==-1){
             cout<<"NO element on stack"<<endl;
             return-1;
         }
         return a[top];
     }
    bool empty(){
        return top==-1;
    }

};
int main()
{

    Stack st;
    st.push(1);
    st.push(2);
    st.push(3);
 
    cout<<st.Top()<<endl;
    st.pop();
    cout<<st.Top()<<endl;
    st.pop();
    st.pop();
    st.pop();
   
    cout<<st.empty()<<endl;
    return 0;
}


Comments