#include二. 主函数using namespace std; #define OK 1 #define ERROR 0 typedef int numbre; //元素类型 typedef int status; //返回状态 typedef struct slnode //链栈节点 { numbre data; //数据部 struct slnode* next; //指针 }slnode,*slist;
int main()
{
slist S;
if (initstack(S) == OK)
cout << "栈创建成功!" << endl;
else cout << "栈创建失败!" << endl;
menu();
while (1)
{
cout << "请输入选项:";
int c;
cin >> c;
if (c == 1)
{
if (input(S) == ERROR)
cout << "进栈错误!" << endl;
else
cout << "进栈成功!" << endl;
}
else if (c == 2)
{
if (deletestack(S) == OK)
cout << "已出栈" << endl;
else
cout << "出栈失败!" << endl;
}
else if (c == 3)
cout << "当前栈顶元素为:" << gettop(S) << endl;
else if (c == 4)
{
if (judgment(S) == OK) cout << "栈为空!" << endl;
else
cout << "栈不为空!" << endl;
}
else
cout << "选项错误!" << endl;
}
return 0;
}
主函数中就是对函数的调用,详情信息请看实现函数。
这是主函数中对栈进行处理的菜单
void menu()
{
cout << "****************************菜单************************" << endl;
cout << "* 1.入栈 2.出栈 3.读取栈顶元素 4.判断栈是否为空 *" << endl;
cout << "********************************************************" << endl;
}
三.实现函数
(1)初始化
status initstack(slist& S)
{
S = NULL;
return OK;
}
链栈并没有头节点,所以S直接为空
(2)入栈status input(slist& S)
{
int n;
cout << "请输入元素个数:";
cin >> n;
slnode* p;
cout << "请输入元素:";
for (int i = 0; i < n; i++)
{
p = new slnode; //
cin >> p->data;
p->next = S; //
S = p; //
}
return OK;
}
建立节点p,将p分配空间,输入p的元素,让p指向第一个S,让p变为S,从而循环进行输入。
(3)出栈
status deletestack(slist& S)
{
slnode* p = new slnode;
if (S == NULL) return ERROR;
cout << S->data;
p = S;
S = S->next;
delete p;
return OK;
}
输出此时S的值,也就是当前的栈顶元素。让p赋为s,S指向下一个。
numbre gettop(slist S)
{
if (S != NULL)
return S->data;
return ERROR;
}
判断是否为空,不为空输出值,不改变链栈,不用加&
(5)判断是否为空栈status judgment(slist S)
{
if (S == NULL) return OK;
return ERROR;
}
本篇文章为一次实验报告要求的内容,已经进行了运行测试。本人正在学习如果有什么问题欢迎讨论斧正。(希望老师如果看到,能了解我的实验并不是在网上抄的啊)
F_NCIAE_A231_2022/3/16



