今天利用swtich语句总体将代码精简了不少
也省去了许多繁杂无用的定义
关于链栈(先进后出)的知识点总结:
1.链表的头指针就是栈顶
2.不需要头结点相较于链表而言
3.基本不存在栈满的情况
4.空栈相当于头指针指向空
5.插入与删除元素仅在栈顶处执行
———————————————————————————————————————————
实现代码:
#include<iostream>
using namespace std;
//链结点数据结构的定义
typedef struct StackNode {
int data;
struct StackNode* next;//嵌套定义
}StackNode,*StackList;
//链栈的初始化
void InitStack(StackList& S) {
S = NULL;
}
//判断链是否为空
bool StackEmpty(StackList S) {
if (S == NULL) return true;
else return false;
}
//链栈的入栈
void Push(StackList& S, int e) {//e为待入栈元素
StackNode* p = new StackNode;//定义节点p的同时分配内存空间
if (p==NULL) cout << "内存分配失败" << endl;
p->data = e;
p->next = S;
S = p;//修改栈顶指针S移动至P处
}
//链栈的出栈
bool Pop(StackList& S, int& e) {
if (StackEmpty(S)) return false;//考虑空栈的异常情况
e = S->data;
StackNode* p = S;//原来结点定义为指针p方便后续的释放操作
S = S->next;//栈顶向下移动一位
free(p);
return true;
}
//链栈的读栈(取栈顶元素)
bool GetTop(StackList S, int& e) {
if (StackEmpty(S)) return false;
e = S->data;
return e;
}
int main() {
StackList S;
InitStack(S);
while (true) {
cout << "1.向栈顶插入元素 " << endl;
cout << "2.删除栈顶元素 " << endl;
cout << "3.判断栈是否为空 " << endl;
cout << "4.读取栈顶元素 " << endl;
cout << "****************** " << endl;
cout << "你想要实现的功能是:" << endl;
int selcet;
cin >> selcet;
switch (selcet){
case 1://入栈
cout << "你想要插入的数值为: " << endl;
int temp1;
cin >> temp1;
Push(S, temp1);
cout << "插入成功" << endl;
system("pause");
system("cls");
break;
case 2://出栈
int temp2;
if (Pop(S, temp2)) cout << "已经删除的元素为:" <<temp2 << endl;
else cout << "该栈为空栈" << endl;
system("pause");
system("cls");
case 3://判断是否为空栈
if (StackEmpty(S)) cout << "该栈为空栈" << endl;
else cout << "该栈不为空栈" << endl;
system("pause");
system("cls");
case 4://读取栈顶元素
int temp3;
if (GetTop(S, temp3)) cout<<"该栈顶元素为: "<<temp3<<endl;
else cout << "该栈为空栈" << endl;
system("pause");
system("cls");
default:
cout << "输入有误,请重新输入" << endl;
break;
}
};
}
实现效果: