簡體   English   中英

使用鏈表實現堆棧時出現分段錯誤

[英]Got Segmentation fault while implementing stack using Linked list

我正在使用鏈表實現堆棧,因為它是在大學時提供給我們的,但由於我對分段錯誤知之甚少,因此無法刪除分段錯誤。 我把我的代碼放在這里。 請告訴我的錯誤和原因,以免重蹈覆轍_/_

#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;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM