我使用一个链表来实现堆栈,因为它是在大学里给我们的,但由于我对分段错误不太了解,所以无法删除分段错误。我把我的代码放在这里。请告诉我的错误和原因,这样就不会再犯这个错误了
#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;
}