Tuesday, 12 May 2015

[CPP] STACK CLASS THAT CAN HANDLE INT AS WELL AS CHAR (& MORE) - GENERIC CLASS

DESCRIPTION 

 A C++ program to implement a generic stack class.  Include a default constructor, destructor and member functions  push( ) to put values into the stack, pop( ) to remove values from stack, isempty( ) and isfull( ) for testing whether stack is empty or full. Use array implementation of stack. Write a main program to test your class for integer and character type data.

PROGRAM


#include <iostream>
using namespace std;


template<class T>
class stack{

private:
    T a[10];
    int top;

public:
  stack(){
        top=-1;
    }

    int isfull(){
        if(top==9)
           return 1;
           return 0;
                } 



 int isempty(){
        if(top==-1)
           return 1;
           return 0;
    }


    void push(T n){
    if(!isfull()){
        top++;
        a[top]=n;
        }
     else {
        cout<<"stack full"<<endl;
     }
    }


      void pop(){
    if(!isempty()){

        cout<<a[top]<<" was popped"<<endl;
        top--;
        }
     else {
        cout<<"stack empty"<<endl;
     }
    }


    ~stack(){
    cout<<"stack destroyed  with top as "<<a[top]<<" having "<<top+1<<" elements"<<endl;
    }
};

int main(){
    int flag=1,temp1;
    char temp2;
stack<int> s1;
stack<char> s2;
do{
cout<<"choose stack 1. int 2.char 3.exit"<<endl;
int ch;
cin>>ch;
if(ch==1){
    cout<<"choose option"<<endl<<"1.push  2.pop"<<endl;
    cin>>ch;
    if(ch==1)
        {
            cout<<"enter data"<<endl;
            cin>>temp1;
            s1.push(temp1);
        }
    else if(ch==2)
        s1.pop();
}

else if(ch==2){
    cout<<"choose option"<<endl<<"1.push  2.pop"<<endl;
    cin>>ch;
    if(ch==1){
 cout<<"enter data"<<endl;
            cin>>temp2;
            s2.push(temp2);
    }
    else if(ch==2)
        s2.pop();
}
else if(ch==3){
    return(0);
}
cout<<"press 1 to continue"<<endl;
cin>>flag;
}while(flag==1);
return 0;
}


No comments:

Post a Comment