问题描述
我正在使用大学里给我们的链表实现堆栈,但是由于我对分段错误的了解不多,所以无法删除分段错误。我将代码放在这里。请告诉我我的错误和原因,以免再次重复此错误_ / _
#include <stdio.h>
#include <stdlib.h>
struct node { int data; struct node *next; };
struct node *top = NULL;
//push function representation
void push (int x) {
struct node*newnode;
newnode = (struct node *) malloc (sizeof (struct node));
newnode->data = x;
newnode->next = top;
top = newnode;
}
//traverse function representation
void traverse ()
{
struct node*temp;
temp = top;
if (top == NULL)
{
printf ("Stack is empty,please push some element");
}
else
{
while (top != NULL)
{
printf ("The element(s) in Stack are %d",temp->data);
temp = temp->next;
}
}
}
//peek function representation
void peek ()
{
if (top == NULL)
{
printf ("Stack is empty");
}
else
{
printf ("Top element is %d",top->data);
}
}
//pop function representation
void pop ()
{
struct node *temp; temp = top;
if (top == NULL)
{
printf ("This is underflow condition");
}
else
{
printf ("%d",top->data);
top = top->next;
free (temp);
}
}
void main ()
{
push (2);
push (4);
traverse ();
peek ();
pop ();
}
解决方法
traverse
函数的这一部分是错误的:
while (top != NULL) // <---- ups
{
printf ("The element(s) in Stack are %d",temp->data);
temp = temp->next;
}
temp
在到达列表末尾时将变为NULL,但是由于对top
进行了检查,因此将取消引用NULL,并且程序将崩溃。
应为:
while (temp != NULL) // <---- fixed
{
printf ("The element(s) in Stack are %d",temp->data);
temp = temp->next;
}