Stack : Template Implementation Using C++

Link Copied To Clipboard !

stack-using-cpp Data Structures

In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed.

Here is an example of stack implemented using c++.


#include<iostream>
#define SIZE 10
using namespace std;

template<typename T> class Stack{
    private:
        int topIndex;
        T* arr;
    public:
        Stack(){
            topIndex = -1;
            arr = new T[SIZE];
            for(int i = 0; i < SIZE; i++){
                *(arr+i) = NULL;
            }
            cout<<"stack created with items limit:"<<SIZE<<endl;
        }

        void push(T item){
            if(topIndex < SIZE -1){
                arr[++topIndex] = item;
                cout<<"pushed "<<item<<" to stack."<<endl;
                return;
            }
            cout<<"stack is full."<<endl;
        }

        void pop(){
            if(topIndex == -1){
                cout<<"stack is empty."<<endl;
                return;
            }
            cout<<"popped "<<arr[topIndex--]<<" from stack."<<endl;
        }

        T top(){
            if(topIndex == -1){
                return NULL;
            }
            return arr[topIndex];
        }
};

int main(){
    //int type stack
    Stack<int> stack;
    bool exit = false;
    do{
        cout<<"===================================="<<endl;
        cout<<"select option :"<<endl;
        cout<<"1 for push"<<endl;
        cout<<"2 for pop"<<endl;
        cout<<"3 for top item"<<endl;
        cout<<"4 for exit"<<endl;
        int ch;
        cin>>ch;
        cout<<"===================================="<<endl;
        switch(ch){
            case 1:
                cout<<"enter value to push"<<endl;
                int num;
                cin>>num;
                stack.push(num);
                break;
            case 2:
                stack.pop();
                break;
            case 3:
                cout<<"top item:"<<stack.top()<<endl;
                break;
            case 4:
                exit = true;
                cout<<"exiting..."<<endl;
                break;
            default:
                break;
        }
    }while(!exit);
    
    return 0;
}

See Also : Stack : Linked List Implementation Using C++


You May Also Like