pranay_teja
6/29/2018 - 12:25 PM

Stack Implementation with Array

#include<bits/stdc++.h>
#define MAX_SIZE 10 //defining max size of stack (since array)
using namespace std;

// #Stack #BasicProblem

bool isEmpty(int topIndex){
    if(topIndex==-1){
        return true;
    }
    return false;
}
bool Full(int topIndex){
    if(topIndex==MAX_SIZE-1){
        return true;
    }
    return false;
}
bool Push(int Stack[],int &topIndex,int push){
    if(Full(topIndex)==true){
        return false;
    }else{
        Stack[topIndex+1]=push;
        topIndex++;
        return true;
    }
}
bool Pop(int &topIndex){
    if(isEmpty(topIndex)==true){
        return false;
    }else{
        topIndex--;
        return true;
    }
}

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;
    int Stack[MAX_SIZE];
    int topIndex=-1; //initializing an empty stack
    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;
                if(Push(Stack,topIndex,push)==true){
                    cout<<"Element successfully pushed"<<endl;
                    if(isEmpty(topIndex)==false){
                        cout<<"Top Element is:"<<Stack[topIndex]<<endl;
                    }
                }else{
                    cout<<"ERROR:  Stack is already full!"<<endl;
                }
        }else if(instruction=="del"){
            if(Pop(topIndex)==true){
                cout<<"Element was successfully popped"<<endl;
                if(isEmpty(topIndex)==false){
                        cout<<"Top Element is:"<<Stack[topIndex]<<endl;
                }else{
                    cout<<"Stack is now Empty!"<<endl;
                }
            }else{
                cout<<"ERROR : Stack is empty!"<<endl;
            }
        }else if(instruction=="top"){
                if(isEmpty(topIndex)==false){
                        cout<<"Top Element is:"<<Stack[topIndex]<<endl;
                }else{
                    cout<<"ERROR : Stack is empty!"<<endl;
                }
        }else{
            cout<<"ERROR : Unknown operation! Please try again"<<endl;
        }
    }
    return 0;
}