ADT栈实现
ADT栈
栈是一种特殊的有序表,其插入删除操作都在同一端(栈顶),由于第一个最后一个插入元素,总是第一个被删除,所以栈友称为后进先出(LIFO)表。
栈的基本操作:建栈,压栈,出栈,栈空,栈满
栈的实现方式:顺序栈,链表栈
1.顺序栈(数组实现):
栈数组实现
1 static const int MAX_STACK_SIZE=1024;
2 static const int MAX_QUEUE_SIZE=1024;
3
4 template <class T>class stack
5 {
6 public:
7 stack():top(-1){}
8 void push(const T &);
9 void pop();
10 T Top();
11 void clear();
12 bool isEmpty();
13 bool isFull();
14 private:
15 T array[MAX_STACK_SIZE];
16 int top;
17
18 };
19
20 template<class T> bool stack<T>::isFull()
21 {
22 if (top>=MAX_STACK_SIZE-1)
23 return true;
24
25 else
26 return false;
27 }
28
29 template<class T> bool stack<T>:: isEmpty()
30 {
31 if (top==-1)
32 return true;
33 else
34 return false;
35 }
36
37 template<class T> void stack<T>::push(const T &value)
38 {
39 if (isFull())
40 {
41 cerr<<"stack full, can't push any more"<<endl;
42 }
43 else
44 {
45 array[++top]=value;
46 }
47
48 }
49
50 template<class T> void stack<T>::pop()
51 {
52 if (isEmpty())
53 cerr<<"stack empty, can't pop"<<endl;
54 else
55 top--;
56 }
57
58 template<class T> T stack<T>::Top()
59 {
60 if(isEmpty())
61 {
62 //return 0;
63 }
64
65 else
66 return array[top];
67 }
68
69 template<class T> void stack<T>::clear()
70 {
71 top=-1;
72 }
2.栈链表实现
栈链表实现
1 template <class T> class list_node
2 {
3 public:
4 T value;
5 list_node *next;
6
7 };
8
9 template<class T> class stack_list
10 {
11 public:
12 stack_list():top(0){}
13 bool isEmpty();
14 bool isFull();
15 void clear();
16 void push(T);
17 void pop();
18 T Top();
19
20 private:
21 list_node<T> *top;
22
23 };
24
25 template<class T> bool stack_list<T>::isEmpty()
26 {
27 if(top)
28 return false;
29 else
30 return true;
31 }
32
33 template<class T>bool stack_list<T>::isFull()
34 {
35
36 }
37
38 template<class T>void stack_list<T>::push(T value)
39 {
40 list_node<T> *newp=new list_node<T>;
41 if(newp==NULL)
42 cerr<<"stack out of space"<<endl;
43 else
44 {
45 newp->value=value;
46 newp->next=top;
47 top=newp;
48 }
49 }
50
51 template<class T> void stack_list<T>::pop()
52 {
53 if (isEmpty())
54 {
55 cerr<<"stack empty,can't pop"<<endl;
56 }
57 else
58 {
59 list_node<T> *p=top;
60 top=top->next;
61 delete p;
62 }
63 }
64
65 template<class T> T stack_list<T>::Top()
66 {
67 if (isEmpty())
68 {
69 //return 0;
70 }
71 else
72 {
73 return top->value;
74 }
75 }
76
77 template<class T> void stack_list<T>::clear()
78 {
79 while (!isEmpty())
80 {
81 pop();
82 }
83 }

浙公网安备 33010602011771号