1
2 #include<iostream>
3 using namespace std;
4 #define SIZE 50
5
6 class Stack
7 {
8 public:
9
10 void creat();
11 void setnull();
12 void get_top(int);
13 void stak_empty();
14 void stak_length();
15 void stak_push();
16 void stak_pop();
17 int stak_destroy();
18 private:
19 char* s;
20 int top;
21
22 };//声明一个堆栈类
23
24 void Stack::setnull()
25 {
26 top=0;
27 }//初始化top的直
28
29 void Stack::creat()
30 {
31 s=new char[SIZE];
32 char ch;
33 cout<<"请输入代码以#结束:"<<endl;
34 ch=cin.get();
35 while(ch!='#')
36 {
37 s[top]=ch;
38 top++;
39 cin>>ch;
40 }
41 top--;
42
43
44 }//建立顺序栈
45
46
47 void Stack::get_top(int flag)
48 {
49
50 if((top<0))
51 {
52 cout<<"堆栈是空的:"<<endl;
53 }
54
55 else if(flag==1)
56 {
57 cout<<"栈被销毁:"<<endl;
58 }
59 else
60 {
61 cout<<"栈顶元素为"<<s[top]<<endl;
62 }
63 }//提取头接点建立
64 void Stack::stak_empty()
65 {
66 if (top<0)
67 {
68 cout<<"堆栈为空:"<<endl;
69
70 }
71 else
72 {
73 cout<<"栈非空:"<<endl;
74 }
75
76
77 }//堆栈为空
78 void Stack::stak_length()
79 {
80 int d;
81 if(top>=0&&top<=(SIZE-1))
82 {
83 d=top+1;
84 cout<<"the length of stack is :"<<d<<endl;
85 }
86 else
87 cout<<"栈不存在或为空:"<<endl;
88 }//栈长度的计算
89
90
91 void Stack::stak_push()
92 {
93
94 char ch;
95 if(top>=(SIZE-1))
96 cout<<"栈已满"<<endl;
97 else
98 {
99 cin>>ch;
100 s[++top]=ch;
101 }
102 }//栈的压入
103
104 void Stack::stak_pop()
105 {
106 char x;
107 if(top<0)
108 {
109 cout<<"栈为空"<<endl;
110 }
111 else
112 {
113 x=s[top--];
114 cout<<x;
115 }
116 }//栈的出列
117
118
119 int Stack::stak_destroy()
120 {
121 int flag; //用来标志是否被毁
122 delete [] s;
123 flag=1;
124 return flag;
125 }
126 int main()
127 {
128 int flag,T;
129 flag=1;
130 T=0;
131 Stack list;
132 list.setnull();
133 list.creat();
134 while(flag)
135 {
136 int i;
137 cout<<"1.get_top(), 2.destory_strak(), 3.stak_empty(),4.stak_length(),5.stak_push(),6.stak_pop():"<<endl;
138 cin>>i;
139 switch(i)
140 {
141 case 1:list.get_top(T);break;
142 case 2:T=list.stak_destroy();break;
143 case 3:list.stak_empty();break;
144 case 4:list.stak_length();break;
145 case 5:list.stak_push();break;
146 case 6:list.stak_pop();break;
147 }
148 cout<<"exit 0 or 1"<<endl;
149 cin>>flag;
150 }
151
152 return 0;
153 system("pause");
154 }
155
156