C语言 为什么我的链表代码产生分割错误时,删除头节点



当从链表的头部删除时,我似乎得到了一个段错误。返回的头部为NULL。它也可能是在其他地方删除的东西,然而,printf语句被打印出来,所以我相信它与没有正确重置头部有关。它通过一次,并从头部删除,然后工作,但第二次不能。

node_t* delete_it(node_t** head, int id){
    node_t* temp;
    node_t* prev = (*head);
    node_t* current = (*head);
    int i = 0;
    //checking to see if the head has the id
    if((*head)->player.player_ID == id){
        printf("removing from the headn");
        temp = (*head);
        (*head) = (*head)->next;
        free(temp);
        return (*head);
    }
    //moving through finding the id
    while(current->player.player_ID != id){
        if(i > 0){
            prev = prev->next;
        }
        //keeps prev pointer the one before current
        i++;
        current = current->next;
        //checking for tail
        if(current->next == NULL && current->player.player_ID == id){
            temp = current;
            free(temp);
            return (*head);
        }
        //removing the node form somewhere inbetween head and tail
        if(current->player.player_ID == id){
            temp = current;
            prev->next = current->next;
            free(temp);
            return (*head);
        }
        return(*head)
    }
}

你的delete_it()函数有很多问题。它不处理NULL指针输入,不以连贯的方式遍历列表,不处理遍历列表时可能出现的所有NULL指针情况,包含一个似乎没有任何用途的变量i,逻辑是混乱的。可以抢救工作:

node_t* delete_it_2(node_t** head, int id){
    node_t* temp;
    node_t* prev = (*head);
    node_t* current = (*head);
    int i = 0;
    //checking to see if the head has the id
    if(*head != NULL && (*head)->player.player_ID == id){
        printf("removing from the headn");
        temp = (*head);
        (*head) = (*head)->next;
        free(temp);
        return (*head);
    }
    //moving through finding the id
    while(current != NULL && current->player.player_ID != id){
        prev = current;
        current = current->next;
    }
    if (current == NULL)
        return *head;
    //checking for tail
    if(current->next == NULL && current->player.player_ID == id){
        free(current);
        prev->next = NULL;
        return (*head);
        }
    //removing the node form somewhere inbetween head and tail
    if(current->player.player_ID == id){
        temp = current;
        prev->next = current->next;
        free(temp);
        return (*head);
    }
    return *head;
}

但是,你不应该抢救它。你的delete_it()函数比它需要的更复杂。我将返回一个指向列表头的指针,就像你所做的那样,但是这样就不需要传递一个指向列表头的双指针了。此外,通过将prev初始化为NULL而不是head并简化逻辑,可以大大简化代码:

node_t * delete_it(node_t *head, int id){
    node_t *temp;
    node_t *prev = NULL;
    node_t *current = head;
    while (current != NULL && current->player.player_ID != id) {
        prev = current;
        current = current->next;
    }
    if (current != NULL) {
        if (prev != NULL) {
            temp = current;
            prev->next = current->next;
        } else {
            temp = head;
            head = head->next;
        }
        free(temp);
    }
    return head;
}

相关内容

  • 没有找到相关文章

最新更新