下面是我做的链栈的基本内容,测试发现打印栈的功能出现了问题,循环体结束之后,程序会异常退出,但是没有找到原因,打印链表的函数我之前一直用在其他文件里面,没出现过这样的问题,但是复制到这里来就用不了了。vs没有报warning或者error。
```c
#include "stdio.h"
#include "stdlib.h"
typedef struct node
{
int data;
struct node* next;
}node;
int push(node* s,int x)
{
if (s)
{
node* p;
p = (node*)malloc(sizeof(node));
p->data = x;
if (s->next == NULL)
s->next = p;
else
{
p->next = s->next;
s->next = p;
}
return 1;
}
return 0;
}
int pop(node* s)
{
if (s->next == NULL)
{
printf("空栈\n");
return 0;
}
node* p;
p = s->next;
s->next = s->next->next;
free(p);
return 1;
}
int displist(node* l)
{
node* p;
if (l)
{
p = l;
while (p->next != NULL)
{
p = p->next;
printf("%d\t", p->data);
}
printf("\n");
return 1;
}
return 0;
}
int init(node* s)
{
s->next = NULL;
return 1;
}
int gettop(node* s)
{
return s->next->data;
}
int main()
{
node* s;
int y, e, status = 0;
exe:
printf("菜单:\n1.栈初始化\t2.入栈\n3.出栈\t4.取栈顶元素\n5.打印栈\n");
scanf("%d", &y);
switch (y)
{
case 1:status = init(&s); break;
case 2:printf("请输入入栈元素:"); scanf("%d", &e); status = push(&s, e); break;
case 3:status = pop(&s); break;
case 4:e = gettop(&s); printf("%d\n", e); break;
case 5:status = displist(&s); break;
default:return 0;
break;
}
if (status == 1)
printf("exe succeeded\n");
else printf("exe failed\n");
goto exe;
return 0;
}
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/225170679846173.png "#left")