首页 > 解决方案 > 双向链表实现显示 C 中的分段错误

问题描述

这是我的 DLL 实现代码片段。

struct node  //doubly-linked list
{
    int data;
    struct node *next; // next-pointer
    struct node *prev; // previous-pointer
};

typedef struct node *node;

struct LL  //LL has a field 'head' pointing to top of the list
{
    node head;

};

typedef struct LL *LL;

node CREATE_NODE(int k)
{
    node temp;
    temp = (node)malloc( sizeof (node));
    
    if (temp == NULL)
    exit(0);

    temp->data= k;
    temp->next = NULL;
    return temp;
}

int main()
{
      LL list;
      list->head = NULL;//segmentation error
      return 0;
}

由于我被要求在问题中使用 typedef 初始化来实现双向链表,有没有其他方法可以初始化头指针以使其为 NULL?

编辑:添加了一些额外的代码来显示插入功能。

void INSERT(LL l, int k) //insert at the front only
   {

    node y;
    y = CREATE_NODE(k); //create an empty list first

    y->next = l->head;  //next-pointer points to the head
    y->prev = NULL;

    if (l->head!= NULL)
    {
       (l->head)->prev = y;
    }

    l->head = y; 
    }

标签: clinked-listsegmentation-fault

解决方案


您的代码存在许多问题。主要的脚射是从这条线上射出的:

typedef struct LL *LL;

现在LL是指向struct LL. 将指针隐藏在 atypedef中被认为是一种非常糟糕的做法,只有可接受的函数指针例外。

因此代码:

LL list;

声明指向 的未初始化指针struct LL。取消引用此指针会list->head调用未定义的行为,这可能是由NULL 取消引用和接收SEGFAULT信号引起的。

我猜目的是:

struct LL list;
list.head = NULL;

推荐阅读