A generic stack class #include #include #include #include using namespace std; #if !defined __STACK_H #define __STACK_H namespace stk{ template class Stack; // Forward declaration of Stack class for overloaded << operator template ostream& operator<<(ostream &,Stack &); // template declaration of << operator template class Stack{ private: T *p; int top,length; string str()const; public: Stack(); Stack(const int); Stack(const Stack&); ~Stack(); void push(T); T pop(); int get_length()const; bool is_empty()const; Stack operator=(const Stack&); // only for basic types friend ostream& operator<< <>(ostream&,Stack &); class StackException{ private: string desc; public: StackException(string exp){ desc="Exception : "+exp; } string get_exp(){ return desc; } }; }; template Stack::Stack(){ top=-1; length=0; p=0; } template Stack::Stack(const int size){ top=-1; length=size; try{ p=new T[length]; }catch(bad_alloc ba){ cout<<"Memory can not be alllocated "; return; } } template Stack::Stack(const Stack &o){ top=o.top; length=o.length; try{ p=new T[length]; }catch(bad_alloc ba){ cout<<"Memory allocation failed "; return; } for(int i=0;i Stack::~Stack(){ if(p!=0) delete [] p; } template void Stack::push(T elem){ if(p==0){ try{ p=new T[1]; }catch(bad_alloc ba){ throw StackException("Memory fault "); } length++; top++; p[top]=elem; } else if(top==(length-1)){ T *q; try{ q=new T[length+1]; }catch(bad_alloc ba1){ throw StackException("Memory fault "); } for(int i=0;i T Stack::pop(){ if(p==0 || top==-1){ throw StackException("Stack empty! "); } T ret=p[top]; top--; length--; if(top==-1){ delete [] p; p=0; } else{ T *q; try{ q=new T[length]; }catch(bad_alloc ba){ throw StackException("Memory fault "); } for(int i=0;i int Stack::get_length()const{ return length; } template bool Stack::is_empty()const{ return ((p==0)? true : false); } template string Stack::str()const{ // private member function if(p==0) return string(""); stringstream ss; for(int i=0;i Stack Stack::operator=(const Stack &stk){ length=stk.length; top=stk.top; if(p!=0) delete [] p; try{ p=new T[length]; }catch(bad_alloc ba){ throw StackException("Memory fault in copying! "); } for(int i=0;i ostream& operator<<(ostream &o,Stack &s){ o<