如何解决使用链表实现堆栈时出现分段错误
我正在使用大学里给我们的链表实现堆栈,但是由于我对分段错误的了解不多,所以无法删除分段错误。我将代码放在这里。请告诉我我的错误和原因,以免再次重复此错误_ / _
#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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。