源码
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
typedef int ElemType;
typedef struct StackNode {
ElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
bool InitStack(LinkStack *S) {
(*S) = (LinkStack) malloc(sizeof(StackNode));
if (*S == NULL) return false;
(*S)->next = NULL;
return true;
}
bool Push(LinkStack S, ElemType e) {
StackNode *p = (StackNode *) malloc(sizeof(StackNode));
if(S->next == NULL) {
p->data = e;
p->next = NULL;
S->next = p;
}
else {
p->next = S->next;
p->data = e;
S->next = p;
}
return true;
}
bool CreateStack(LinkStack S) {
ElemType e;
scanf("%d", &e);
while (e != 9999) {
Push(S, e);
scanf("%d", &e);
}
return true;
}
bool Pop(LinkStack S, ElemType *e) {
if (S == NULL || S->next == NULL) return false;
StackNode *p = S->next;
S->next = p->next;
free(p);
return true;
}
bool GetTop(LinkStack S, ElemType *e) {
if(S == NULL || S->next == NULL) return false;
*e = S->next->data;
return true;
}
bool PrintStack(LinkStack S) {
if (S == NULL || S->next == NULL) return false;
StackNode *p;
p = S->next;
while (p != NULL) {
printf("%d\n", p->data);
p = p->next;
}
return true;
}
int main() {
LinkStack S;
InitStack(&S);
printf("链栈初始化成功!\n");
int chooseNumber;
ElemType e;
bool ans;
while (1) {
printf("******************************\n");
printf("请操作:\n");
printf("1(Create):创建栈\n");
printf("2(Push):入栈\n");
printf("3(Pop):出栈\n");
printf("4(Get):取栈首元素\n");
printf("5(Print):输出栈\n");
printf("0(exit):退出程序\n");
printf("******************************\n");
scanf("%d", &chooseNumber);
switch (chooseNumber) {
case 0:
exit(0);
break;
case 1:
printf("请按顺序输入要入栈的元素来创建一个栈,输入9999结束\n");
CreateStack(S);
PrintStack(S);
break;
case 2:
printf("请输入入栈元素:\n");
scanf("%d", &e);
ans = Push(S, e);
if (ans) printf("入栈成功!\n");
else printf("入栈失败!\n");
break;
case 3:
ans = Pop(S, &e);
if (ans) printf("出栈成功!出栈元素为%d\n", e);
else printf("出栈失败!\n");
break;
case 4:
ans = GetTop(S, &e);
if (ans) printf("栈顶元素为%d\n", e);
else printf("栈为空!\n");
break;
case 5:
ans = PrintStack(S);
if (ans) printf("当前栈元素如下:\n");
else printf("栈为空!无输出!\n");
break;
default:
printf("输入错误,请重新输入:\n");
break;
}
}
return 0;
}