adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C++ to implement stack Using Template feature.


Program in C++ to implement stack Using Template feature.


#include<iostream>
#include<conio.h>
 using namespace std;
 template <class T>
  class stack
   {
      T *a;
   int top,size;
  public:
     stack()
       {
        top=-1;
        size=25;
        a=new T[size];
        for(int i=0;i<size;i++)
         a[i]=0;
    }
   stack(int s)
       {
        top=-1;
        size=s;
        a=new T[size];
        for(int i=0;i<size;i++)
            a[i]=0;
    }
   ~stack(){}
           void push(T n)
            {
             if(top==size-1){
                cout<<"\n Stack overflow ";
                return;
              }
                 top++;
                 a[top]=n;
             }
            void pop()
            {
              if(top==-1){
               cout<<"\n Stack underflow";
               return;
              }
                 cout<<"\n Delete data is "<<a[top];
                 top--;
            }
        void showRev()
         {
            int i;
             if(top==-1){
                 cout<<"\n Stack underflow ";
                 return;
             }
            cout<<"\nEntered stack elements is ";
           for(i=0;i<=top;i++)
            cout<<a[i]<<"   ";
         }
         void show()
         {
            int i;
             if(top==-1){
               cout<<"\nStack underflow";
                return;
           }
          cout<<"\nEntered stack elements is ";
            for(i=top;i>=0;i--)
             cout<<a[i]<<"   ";
         }
        int length()
         {
             return (top+1);
         }
    };

   int main()
   {
        stack<int> s1;
        s1.push(23);
        s1.push(56);
        s1.push(45);
        s1.push(99);
        s1.show();
        cout<<endl<<"Length of stack = "<<s1.length();
        stack<float> s2(10);
        s2.push(2.3);
        s2.push(5.6);
        s2.push(4.5);
        s2.push(96.9);
        s2.push(12.8);
        s2.push(18.6);
        s2.show();
        cout<<endl<<"Length of stack = "<<s2.length();
        s2.pop();

        stack<char> s3(10);
        s3.push('w');
        s3.push('D');
        s3.push('U');
        s3.push('G');
        s3.show();
        cout<<endl<<"Length of stack = "<<s3.length();
        s3.pop();
        return 0;
   }
Output :-







Related Programs
  1.  Program in C and C++ to implement stack Using Array .
  2.  Program in C and C++ to implement stack Using Structure and Class.
  3.  Program in C and C++ to implement stack Using Array and Function.
  4.  Program in C and C++ to sort stack using one temporary stack.
  5.  Program in C++ to implement stack Using Template feature.

Post a Comment

0 Comments