// 链栈的基本操作
#include <iostream>
#include <fstream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef char SElemType;
// 定义链栈类型
typedef struct StackNode {
SElemType data;
struct StackNode *next;
}StackNode,*LinkStack;
// 初始化链栈
Status InitStack(LinkStack &S) {
S = NULL;
return OK;
}
// 入栈
Status Push(LinkStack &S, SElemType e) { // 在栈顶插入元素e
LinkStack p;
p = new StackNode; // 生成新结点
p->data = e; // 将新结点数据域赋值为e
p->next = S; // 将新结点插入栈顶
S = p; // 修改栈顶指针为p
return OK;
}
// 出栈
Status Pop(LinkStack &S, SElemType &e) { // 删除S的栈顶元素,有e返回其值
LinkStack p;
if (S == NULL)
return ERROR;
e = S->data; // 将栈顶元素赋给 e
p = S; // 用p临时保存栈顶元素的空间,方便释放
S = S->next; // 修改栈顶指针
delete p; // 释放原栈顶元素的空间
return OK;
}
// 取栈顶元素值
SElemType GetTopValue(LinkStack S) {
if (S != NULL)
return S->data; // 返回栈顶元素的值,栈顶指针不变
}
int main()
{
LinkStack S=NULL;
int choose, flag = 0;
SElemType j, t;
cout << "1.初始化栈 2.入栈 3.读取栈顶元素 4.出栈 0.退出\n\n";
choose = -1;
while (choose != 0) {
cout << "\n请选择0-4项:";
cin >> choose;
switch (choose) {
case 1:
if (InitStack(S))
{
flag = 1;
cout << "链栈已初始化成功." << endl << endl;
}
else
cout << "链栈初始化失败." << endl << endl;
break;
case 2: {
fstream file;
file.open("ChainStack.txt");
if (!file) {
cout << "文件打开失败,请重新检查.\n\n";
exit(ERROR);
}
if (flag) {
flag = 1;
cout << "进栈元素依次为:" << endl;
while (!file.eof()) {
file >> j;
if (file.fail())
break;
else
{
Push(S, j);
cout << j << " ";
}
}
cout << "\n\n\n";
}
else
cout << "链栈未创建,请重新选择." << endl << endl;
file.close();
}
break;
case 3:
if (flag != -1 && flag != 0)
cout << "栈顶元素为:" << GetTopValue(S) << endl << endl;
else
cout << "栈中无元素,请重新选择." << endl << endl;
break;
case 4:
if (flag) {
cout << "依次出栈元素为:" << endl;
while (Pop(S, t))
cout << t << " ";
cout << endl << endl;
}
else
cout << "链栈未创建,请重新选择\n\n";
break;
}
}
return 0;
}