链式栈

头文件
 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
main.cpp
 1 #include<iostream>
2 #include"linkedStack.h"
3
4 using namespace std;
5
6 int main()
7 {
8
9
10 cout << "测试链式栈"<< endl;
11 LinkedStack<int> s;
12 s.Push(10);
13 cout << s.Top() << endl;
14 s.Push(20);
15 cout << s.Top() << endl;
16 s.Push(30);
17 cout << s.Top() << endl;
18 s.Pop();
19 cout << s.Top() << endl;
20 s.MakeEmpty();
21 s.Push(300);
22 cout << s.Top() << endl;
23 return 0;
24 }



posted @ 2012-03-27 23:47  uniquews  阅读(199)  评论(0编辑  收藏  举报