删除链表中的节点 - 分段错误 [英] Deleting node in linked list - segmentation fault

查看:62
本文介绍了删除链表中的节点 - 分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题需要从链表中删除节点给定链表的头指针和要删除的链表中节点的位置.有关问题的更多详细信息,请访问:https://practice.geeksforgeeks.org/problems/delete-a-node-in-single-linked-list/1

Problem requires to delete node from linked list given head pointer of list and the position of node in list to be deleted. More details of question can be found at: https://practice.geeksforgeeks.org/problems/delete-a-node-in-single-linked-list/1

代码返回分段错误,但不确定我哪里出错了.我的代码如下:

Code returns segmentation fault but not exactly sure where I went wrong. My code is as follows:

Node* deleteNode(Node *head,int x)
{
    //Your code here
    struct Node* temp = head;

    if(x==0){
        //change head
        head = temp->next;
        free(temp);
    }
    //find previous node of node to be deleted
    for(int i=0; temp!=NULL && i<x-1; ++i){
        //traverse
        temp = temp->next;
    }
    //now temp should be pointing to previous node
    //store pointer to next of node to be deleted
    struct Node* next = temp->next->next;
    free(temp->next);
    temp->next= next;
}

推荐答案

您的代码包含许多可以取消引用空指针的地方.例如这里:

Your code contains many places where a null pointer could be dereferenced. For example here:

struct Node* temp = head;

if(x==0){
    //change head
    head = temp->next;
    free(temp);
}

如果 head 已经是一个空指针.此外,您似乎假设这会更改 caller 中的 head 变量,但事实并非如此.你必须通过一个双指针来实现这一点.最后,看起来您的函数应该在 free(temp); 之后返回.

if head was already a null pointer. Furthermore, you seem to be assuming that this changes the head variable in the caller, which is not the case. You would have to pass a double-pointer to achieve this. Lastly, it looks like your function should return after the free(temp);.

然后,看这部分:

for(int i=0; temp!=NULL && i<x-1; ++i){
    //traverse
    temp = temp->next;
}
//now temp should be pointing to previous node
//store pointer to next of node to be deleted

不,它不一定指向一个节点,temp 也可以包含一个空指针,这是 for 循环的第二个中断条件.如果是这种情况,您必须检查并退出.

No, it not necessarily points to a node, temp could also contain a null pointer, which is the second break condition of your for-loop. You have to check for that and bail out if this is the case.

这篇关于删除链表中的节点 - 分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆