链栈的实现(无头)
实现一个char型的链栈栈,并完成其基本操作:Init,Push,Pop,GetTop,Traverse,Clear,Destroy, IsEmpty。请自行设计main函数以测试各个基本操作。
本题中的链栈遍历为栈顶到栈底遍历打印,具体实现从栈底到栈顶打印参考我另一篇文章
#include <iostream>
using namespace std;
typedef char ElemType; //每个栈元素的数据类型
typedef struct StackNode { //栈元素结点定义
ElemType data; //结点数据
StackNode* next; //结点链接指针
}*LinkStack; //链式栈
void InitStack(LinkStack& S) { //栈初始化
S = NULL; //栈顶(链头)指针置空
}
int IsEmpty(const LinkStack& S) { //判栈空否
return S == NULL;
}
int Push(LinkStack& S, ElemType &e) { //进栈
StackNode* s = new StackNode;
if (!s) exit(1); //可省略
s->data = e; //结点赋值
s->next = S; S = s; //链入栈顶
return 1;
}
int Pop(LinkStack& S, ElemType& e) { //出栈
if (IsEmpty(S)) return 0;
StackNode* q = S;
S = q->next; e = q->data; //摘下原栈顶
delete q; return 1; //释放原栈顶结点
}
int GetTop(const LinkStack& S, ElemType& e) {
if (IsEmpty(S)) return 0;
e = S->data; return 1;
} //看栈顶
void Traverse(const LinkStack&S) {
//本题,目前也可以将链栈的Traverse设计成从栈顶到栈底遍历打印。
StackNode* p;
p = S;
while (p) {
cout << p->data << endl;
p = p->next;
}
}
int Clear(LinkStack& S) {
StackNode* p;
while (S->next) {
p = S->next;
S->next = p->next;
delete(p);
}
S = NULL;
return 1;
}
int Destroy(LinkStack& S) {
StackNode* p = S;
while (p){
S = S->next;
delete(p);
p = S;
}
return 1;
}
int main(){
cout << "=====定义一个栈S=====" << endl;
LinkStack S;
char e='a';
char a = 'a'; char b = 'b'; char c = 'c'; char d = 'd'; char f = 'e';
cout << "=====初始化该栈S=====" << endl;
InitStack(S);
cout << "=====判断S是否是空栈:=====" << endl;
if (IsEmpty(S)) {
cout << "S是空栈" << endl;
}
else {
cout << "S不是空栈" << endl;
}
cout << "=====入栈a,b,c,d,e=====" << endl;
Push(S, a);
Push(S, b);
Push(S, c);
Push(S, d);
Push(S, f);
cout << "=====取栈顶的值并打印:=====" << endl;
GetTop(S, e);
cout << "栈顶的值为:" << e << endl;
cout << "=====遍历该栈:=====" << endl;
Traverse(S);
cout << "=====出栈一个值:=====" << endl;
Pop(S, e);
cout << "=====遍历该栈:=====" << endl;
Traverse(S);
cout << "=====取栈顶的值并打印:=====" << endl;
GetTop(S, e);
cout << "栈顶的值为:" << e << endl;
cout << "=====清空该栈=====" << endl;
Clear(S);
cout << "=====遍历该栈:=====" << endl;
Traverse(S);
cout << "=====销毁该栈:=====" << endl;
if (Destroy(S)) {
cout << "销毁栈成功" << endl;
}
else {
cout << "销毁栈失败" << endl;
}
}