1 #ifndef LINKEDSTACK_H
2 #define LINKEDSTACK_H
3
4 template<class T> class LinkedStack;//前置声明
5
6 template<class T>
7 class ChainNode
8 {
9
10 friend LinkedStack<T>;
11 private:
12 ChainNode(const T& theData, ChainNode *n = 0):data(theData), link(n){}//构造函数
13 T data;
14 ChainNode<T> *link;
15
16 };
17 template<class T>
18 class LinkedStack
19 {
20 public:
21
22 LinkedStack() : top(0){}
23 //~LinkedStack() {MakeEmpty();}//把堆栈里所有节点都删除掉
24
25 bool IsEmpty() const;
26 T& Top() const;
27 void Push(const T& e);
28 void Pop();
29 void MakeEmpty();
30 private:
31
32 ChainNode<T> *top;
33 };
34
35
36 template<class T>
37
38 bool LinkedStack<T>::IsEmpty() const
39 {
40
41 return top == 0;
42 }
43
44 template <class T>
45 void LinkedStack<T>::Push(const T &e)
46 {
47
48 //top指针指向新放的数据
49 top = new ChainNode<T>(e,top);
50
51 }
52
53 template<class T>
54 T& LinkedStack<T>::Top() const
55 {
56
57
58 if(IsEmpty())
59 throw "Stack is empty";
60 return top->data;
61 }
62
63 template<class T>
64 void LinkedStack<T>::Pop()
65 {
66 if(IsEmpty())
67 throw "Cannot delete";
68 ChainNode<T> *delNode = top;
69 top = top->link;
70 delete delNode;//和new相对应
71
72 }
73
74 template<class T>
75 void LinkedStack<T>::MakeEmpty()
76 {
77
78 while(!IsEmpty())
79 Pop();
80 }
81 #endif