C++ 链栈 基本算法实现
C++ 链栈 基本算法实现
#ifndef LinkStack_h #define LinkStack_h #includetemplate <class T> struct Node{ T data; struct Node * next; }; template <class T> class LinkStack{ public: LinkStack() {top = NULL;} ~LinkStack(); void Push (T x); T Pop(); T GetTop(); bool Empty() { return (NULL == top)? true:false;} private: struct Node *top; }; template <class T> void LinkStack ::Push (T x){ struct Node * p = new Node ; p->data = x; p->next = top; top = p; } template <class T> T LinkStack :: Pop(){ if(Empty()) throw "下溢"; T x = top->data; struct Node * p = top; top = top->next; delete p; return x; } template <class T> LinkStack ::~LinkStack(){ while(top){ struct Node *p = top; top = top-> next; delete p; } } template <class T> T LinkStack ::GetTop(){ if(Empty()) throw "溢出"; return top->data; } #endif /* LinkStack_h */