Tuesday, October 21, 2014

Implement stack program with template

#include<iostream.h>
#define size 100
template<class T>
class stack
{
    private: int top;
                T item[size];
    public:
                stack()
                {
                    top=-1;
                }

                void push(T x)
                {
                    if(top==size-1)
                    cout<<"\n Stack overflow";
                    else
                    item[++top]=x;
                }
                T pop()
                {
                    if(top==-1)
                    cout<<"\n Stack underflow";
                    else
                    return(item[top--]);
                }
                void show()
                {
                    int k;
                    cout<<"\n Output=";
                    for(k=top;k>=0;k--)
                    cout<<"->"<<item[k];
                }
};
void main()
{  int n;
    cout<<"Charcter stack.................\n";
    stack<char> s1;
    char c;
    cout<<"\n Enter no.of value=";
    cin>>n;
    cout<<"\t\tFor character.....";
    for(int i=0;i<n;i++)
    {
        cout<<"\nEnter char=";
        cin>>c;
        s1.push(c);
    }
    s1.show();
    cout<<"\nItem remove="<<s1.pop();
    s1.show();

    cout<<"\n\nFloating stack..................";
    stack<float> s2;
    cout<<"\n\t\tFor floating point....";
    s2.push(1.1);
    s2.push(1.2);
    s2.push(1.3);


    s2.show();
    cout<<"\nItem remove="<<s2.pop();
    s2.show();

    cout<<"\n\nInteger stack.........................";
    stack<int> s3;
    cout<<"\n\t\tFor integer point....";
    s3.push(1);
    s3.push(2);
    s3.push(2);


    s3.show();
    cout<<"\nItem remove="<<s3.pop();
    s3.show();

}

No comments:

Post a Comment