#include #include void Exception(int Condition, char *ErrorMsg){ if(Condition){cerr << ErrorMsg << endl; abort();} } template class AbsStack{ public: AbsStack(){} //默然构造函数 virtual ~AbsStack(){} //析构函数 virtual bool IsEmpty() const = 0; //判栈空 virtual bool IsFull() const = 0; //判栈满 virtual void MakeEmpty() = 0; //将栈清空 virtual void Push( ElemType &x) = 0; //进栈 virtual void Pop() = 0; //出栈 virtual const ElemType &Top() = 0; //取顶点元素 private: AbsStack(const AbsStack &){}; //冻结复制构造函数 }; static const int InitStackSize = 10; template class Stack:public AbsStack{ public: Stack(); //构造函数 ~Stack(){ delete []Array;} //析构函数 bool IsEmpty() const {return top == -1;} //判栈空 bool IsFull() const {return top == MaxSize - 1;} //判栈满 void MakeEmpty() {top = -1;} //将栈清空 void Push( ElemType &x); //进栈 void Pop(); //出栈 const ElemType &Top(); //取顶点元素 const Stack &operator=(const Stack &R); private: ElemType *Array; //存放结点的数组名 int top; //栈顶指针 int MaxSize; //栈的容量 void DoubleArray(int Max); //更新数组的容量 }; template Stack::Stack():top(-1),MaxSize(InitStackSize){ //构造函数,空间大小为MaxSize Array = new ElemType[MaxSize]; } template const ElemType &Stack::Top(){ //读取栈顶结点 Exception(IsEmpty(), "Underflow:Stack is empty!"); return Array[top]; } template void Stack::Push( ElemType &x){ if(top + 1 == MaxSize) DoubleArray(2*MaxSize); Array[++top] = x; //新结点放入新的栈顶位置 } template void Stack::Pop(){ //将栈顶元素出栈 Exception(IsEmpty(), "Stack is underflow!"); top--; } template const Stack &Stack::operator=(const Stack &R){ if(this == &R) return *this; delete []Array; Array = new EleemType[R.MaxSize]; //分配存储单元 top = R.top; for(int j=0; j<=top; j++)Array[j] = R.Array[j]; //逐个复制结点 return *this; } template void Stack::DoubleArray(int Max){ ElemType *oldarr = Array; Exception((MaxSize >= Max), "New size is too small!"); Array = new ElemType[Max]; for(int k=0; k<=top; k++) Array[k] = oldarr[k]; //逐个复制结点 MaxSize = Max; delete []oldarr; return; } int main() { }