【发布时间】:2020-12-15 16:42:22
【问题描述】:
我在 C 中创建堆栈操作。但是当我试图弹出最后一个元素时,它会导致 SEGMENTATION FAULT。
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct node1
{
int data;
struct node1 *link;
} node;
node *top,*header;
void push()
{
node *temp = (node *)malloc(sizeof(node));
printf("PUSH : ");
scanf("%d", &temp->data);
if (header == NULL)
{
top = temp;
header = temp;
temp->link = NULL;
}
else
{
temp->link = header;
header = temp;
top = temp;
}
}
void pop()
{
if (header == NULL)
printf("Stack Empty");
else
{
node *ptr = top;
top = header = top->link;
free(ptr);
}
}
void display()
{
node *ptr = header;
while (1)
{
if (ptr->link == NULL)
{
printf("%d", ptr->data);
break;
}
printf("%d", ptr->data);
ptr = ptr->link;
printf("->");
}
printf("\n\n");
}
int main()
{
printf("\nSTACK :\n\n");
while (1)
{
int choice;
printf("1.Push 2. Pop (Press ctrl + C to exit ): ");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
default:
printf("Wrong Entry\n\n");
}
}
}
我知道有人问过Pop Function In Linked List Stack Results in Segmentation Fault- C 的类似问题,但这对我没有帮助。为什么会出现这个错误?问题是否与上述问题类似。
【问题讨论】:
-
这些声明节点 *top, *rear, *front, *header;没有意义。
-
函数显示可以调用未定义的行为。
-
@Vlad fom Moscow 编辑了它
-
指针top和head互相复制是什么意思?
-
您需要分别编写堆栈和队列的实现。
标签: c stack singly-linked-list