源码
#include
#include
#include
//#define bool char
//#define false 0
//#define true 1
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) { //输入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("%dn", 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("出栈成功!出栈元素为%dn", e);
else printf("出栈失败!n");
break;
case 4: //取栈顶元素
ans = GetTop(S, &e);
if (ans) printf("栈顶元素为%dn", e);
else printf("栈为空!n");
break;
case 5: //输出栈
ans = PrintStack(S);
if (ans) printf("当前栈元素如下:n");
else printf("栈为空!无输出!n");
break;
default:
printf("输入错误,请重新输入:n");
break;
}
}
return 0;
}