//定义,初始化,判空,入栈,出栈,读栈顶
#include <stdio.h>
#include <malloc.h>
#define _CRT_SECURE_NO_WARNINGS
//#include <stdbool.h>
#define Max_Size 20
typedef struct Snode {
int data;//data
struct Snode* next;//指针域
}Snode, * LinkStack;
bool InitStack(LinkStack& s) {//初始化
s = (Snode*)malloc(sizeof(Snode));
s->next = NULL;
return true;
}
bool StackEmpty(LinkStack s) {//判空
if (s->next == NULL) {
return true;
}
else {
return false;
}
}
bool Push(LinkStack& s, int x) {//入栈
Snode* p = (Snode*)malloc(sizeof(Snode));
p->data = x;
p->next = s->next;
s->next = p;
return true;
}
bool Pop(LinkStack& s, int& x) {
// 出栈
if (StackEmpty(s)) { // 修改判断条件为 if (StackEmpty(s))
printf("栈空");
return false;
}
else {
Snode* p = s->next;
x = p->data;
s->next = p->next;
free(p);
return true;
}
}
bool GetPop(LinkStack s, int& x) {
if (StackEmpty(s) ) {
printf("栈空");
return false;
}
else
{
Snode* p = s->next;
x = p->data;
//s->next = p->next;
return true;
}
}
bool AllGet(LinkStack s, int& x) {
Snode* p;
if (StackEmpty(s) != false) {
printf("栈空");
return false;
}
else {
while (s->next != NULL) {
p = s->next;
x = p->data;
printf("x=%d ", x);
s = s->next;
}
}
}
int main() {
LinkStack s;
int choice, x;
InitStack(s); // 初始化栈
printf("请选择操作:\n");
printf("1. 入栈\n");
printf("2. 出栈\n");
printf("3. 遍历栈\n");
printf("4. 判空\n");
printf("0. 退出\n");
scanf_s("%d", &choice);
while (choice != 0) {
switch (choice) {
case 1:
printf("请输入要入栈的元素值: ");
scanf_s("%d", &x);
if (Push(s, x)) {
printf("入栈成功! 栈顶元素为: %d\n", s->next->data);
}
else {
printf("入栈失败!\n");
}
break;
case 2:
if (Pop(s, x)) {
printf("出栈元素为: %d\n", x);
}
else {
printf("出栈失败,栈为空!\n");
}
break;
case 6:
if (GetPop(s, x)) {
printf("栈顶元素为: %d\n", x);
}
else {
printf("栈为空!\n");
}
break;
case 3:
AllGet(s, x);
break;
case 4:
if (StackEmpty(s)) {
printf("栈为空!\n");
}
else {
printf("栈不为空!\n");
}
break;
default:
printf("无效的选择,请重新输入!\n");
}
printf("\n请选择操作:\n");
scanf_s("%d", &choice);
}
// 释放内存
Snode* temp;
while (s->next != NULL) {
temp = s->next;
s->next = s->next->next;
free(temp);
}
free(s);
return 0;
}