#include"pch.h"
#include<iostream>
using namespace std;
typedef int ElemType;
typedef struct StackNode {
ElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
//1.初始化
bool InitStack(LinkStack &S) {
S = NULL;
return true;
}
//2.入栈
bool Push(LinkStack &L, ElemType e) {
StackNode *p = new StackNode;
p->data = e;
p->next = L;
L = p;
return true;
}
//3.取顶
ElemType GetTop(LinkStack S) {
if (S != NULL)
return S->data;
}
//4.常规遍历
void GetAll(LinkStack S) {
if (S == NULL) cout << "栈空" << endl;
int time = 0;
while (S != NULL) {
cout << S->data << " ";
S = S->next;
++time;
}
cout << "总共有" << time << endl;
}
//5.递归遍历,分支法
void GetAll2(LinkStack S) {
if (S == NULL) {
cout << endl; return;
}
else {
cout << S->data << " ";
GetAll2(S->next);
}
}
//5.1递归遍历,分支法
void GetAll3(LinkStack S) {
if (S) {
cout << S->data << " ";
GetAll3(S->next);
}
else {
cout << endl;
return;
}
}
//6.出栈
bool Pop(LinkStack &S, ElemType & e) {
if (!S) return false;
e = S->data;
LinkStack temp = S;
S = S->next; delete temp;
return true;
}
//主函数
int main() {
LinkStack S; ElemType e;
if (InitStack(S)) cout << "Succeed" << endl;
else cout << "failed" << endl;
//入栈
cout << "input e\t";
while (cin >> e) {
Push(S, e);
cout << "input e\t";
}
cout << "栈顶元素" << GetTop(S) << endl;
cout << "遍历1" << endl; GetAll(S);
cout << "遍历2" << endl; GetAll2(S);
cout << "遍历3" << endl; GetAll3(S);
//出栈
cout << "出栈" << endl;
if (Pop(S, e)) {
cout << "e=" << e << endl;
}
cout << "遍历1对剩下的元素" << endl; GetAll(S);
}