Search Here

C++ program to implement Stack using Template

/* C++ program Stack using Template */

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

template <class TYPE>
class stack
{
    TYPE A[SIZE];
    int stack_top;

    public: stack();
            void push(TYPE);
            void pop();
            void top();
};

template <class TYPE>
stack<TYPE> :: stack()
{
    stack_top=-1;
    for(int i=0;i<SIZE;i++)
        A[i]=0;
}

template <class TYPE>
void stack<TYPE> :: push(TYPE item)
{
    if(stack_top==SIZE-1)
        cout<<"\nStack Overflow";
    else
        A[++stack_top]=item;
}

template <class TYPE>
void stack<TYPE> :: pop()
{
    if(stack_top==-1)
        cout<<"\nStack Underflow";
    else
        cout<<"\nPopped item is "<<A[stack_top--];
}

template <class TYPE>
void stack<TYPE> :: top() //Displays only top most element
{
    if(stack_top==-1)
        cout<<"\nStack empty";
    else
        cout<<"\nA[stack_top]="<<A[stack_top];
}

int main()
{
    stack<int> s;
    while(1)
    {
        cout<<"\n\t1.PUSH\t2.POP\t3.TOP\t4.Exit";
        cout<<"\n\t\tEnter choice: ";
        int ch;
        cin>>ch;
        switch(ch)
        {
            case 1: cout<<"\nEnter item to insert :";
                    int item;
                    cin>>item;
                    s.push(item);
                    break;
            case 2: s.pop();
                    break;
            case 3: s.top();
                    break;
            case 4: return 0;
            default: cout<<"\nERROR: Wrong choice";
        }
    }
}


Stack using Template
Output

No comments:

Post a Comment