c - 段错误 - 链表

标签 c list linked-list segmentation-fault

我正在学习如何在C中构建链表。我的程序可以编译,但由于某种原因我无法弄清楚,我遇到了段错误。我已经尝试解决这个问题有一段时间了,但我没有任何运气。这是错误的代码:

int len()
{
    struct list * current = head;
    int length = 0; 

    while (current != NULL)
    {
        length++;
        current = current -> next; //move to next node
    }
    return length; 
}


struct list * search ( int key)
{
    struct list * current = head;

    while (current != NULL && current->data != key)
        current = current -> next;

    if (current != NULL && current -> data == key)
        return current;
    return NULL;
}



/* Insert a new data element with key d into the end of the list. */
void insert(int d )  //  at the end
{
    struct list * current = head; 
    struct list * new;
    while (current -> next != NULL)
        current = current -> next;
    new = (struct list *)malloc(sizeof(struct list));
    new -> data = d; 
    current -> next = new;
    new -> next = NULL;     
}


void insertAfter(int d, int where )  //  insert at the middle
{
    struct list * marker = head;
    struct list * new;

    while(marker -> data != where)
        marker = marker -> next;
    new = (struct list*)malloc(sizeof(struct list));

    new -> next = marker -> next; 
    marker -> next = new;
    new -> data = d; 
}


/* Remove the node with value d from the list */
/* assume no duplicated keys in the list */
/* If the list is empty, call prtError() to display an error message and return -1. */

void delete(int d)
{
    struct list * current1 = head; 
    struct list * current2;

    if (len() == 0)
    { //prtError("empty");
        exit(0);
    }
    if (head -> data == d)
    { 
        head = head -> next;
    }

    //Check if last node contains element
    while (current1->next->next != NULL)
        current1 = current1->next;

    if(current1->next->data == d)
            current1->next == NULL; 


    current1 = head; //move current1 back to front */

    while(current1 -> next -> data != d)
        current1 = current1 -> next; 

    current2 = current1 -> next;
    current1 -> next = current2 -> next; 

}

我在以下行的删除方法中遇到段错误:

while(current1 -> next -> data != d)

为什么这是错误的?

最佳答案

您有几个问题,请在插入中:

while (current -> next != NULL)

您没有检查current是否为NULLdelete 中也存在类似问题:

if (head -> data == d)

您需要在此处检查head并且:

while (current1->next->next != NULL)

也是一个问题。

关于c - 段错误 - 链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558634/

相关文章:

c - 可以访问继承结构的结构

c++ - 在 c 中复制数组与复制 int 成本和性能

c - 使用命令行参数的结构链接列表

c - Linux中的共享内存锁(C语言)

我可以使用 &array[0][0][0] 传递声明为 double ***array 的 3D 数组吗?

list - 这个名为 "picks"的函数背后的逻辑是什么?

excel - 复制并粘贴回excel中的过滤列表

c# - 在c#中使用字符串数据类型列表创建元组

java - 在迭代列表时从列表中删除对象

C++:递归追加链表