pranay_teja
6/29/2018 - 12:08 PM

Stack Implementation with Vector PopBack

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

// #Stack #BasicProblem

bool Top(vector<int> &a,int &top){
    if(a.size()==0){
        return false;
    }else{
        top=a[a.size()-1];
    }
}
void Push(vector<int> &a,int push){
    a.push_back(push);
}
bool Pop(vector<int> &a){
    if(a.size()==0){
        return false;
    }else{
        a.pop_back();
    }
}
int main(){
    cout<<"Instructions: \n";
    cout<<"Type add to push onto stack"<<endl;
    cout<<"Type del to pop from stack"<<endl;
    cout<<"Type top to check the top element in stack"<<endl;
    cout<<"Type exit to stop using the stack"<<endl;
    vector<int> Stack;
    int top;
    while(1){
        string instruction;
        cout<<"Instruction: ";
        cin>>instruction;
        if(instruction=="exit"){
            break;
        }else if(instruction=="add"){
            cout<<"Enter the element top be pushed"<<endl;
            int push; //element to be pushed
            cin>>push;
            Push(Stack,push);
                cout<<"Element successfully pushed"<<endl;
                if(Top(Stack,top)==true){
                    cout<<"Top Element is:"<<top<<endl;
                }

        }else if(instruction=="del"){
            if(Pop(Stack)==true){
                cout<<"Element was successfully popped"<<endl;
                if(Top(Stack,top)==true){
                    cout<<"Top Element is:"<<top<<endl;
                }else{
                    cout<<"Stack is now Empty!"<<endl;
                }
            }else{
                cout<<"ERROR : Stack is empty!"<<endl;
            }
        }else if(instruction=="top"){
                if(Top(Stack,top)==true){
                    cout<<"Top Element is:"<<top<<endl;
                }else{
                    cout<<"ERROR : Stack is empty!"<<endl;
                }
        }else{
            cout<<"ERROR : Unknown operation! Please try again"<<endl;
        }
    }
    return 0;
}