简体   繁体   English

C - 节点去除问题中的单链表

[英]singly-linked list in C - node removal problem

I'm implementing a singly-linked list in C and got stuck with the remove node function. 我在C中实现了一个单链表,并且卡在了删除节点功能上。 It removes the element, links two of its neighbours, but the following node gets the next node address set to NULL. 它删除元素,链接其两个邻居,但是下一个节点将下一个节点地址设置为NULL。 Why? 为什么? Can anybody help? 有人可以帮忙吗?

  struct node{
        struct node* next;
        int value;
    };

    struct list{
        struct node* head;
        struct node* tail;
    };

void remove_node(struct list* plist, int value){

    struct node* current;
    struct node* temp;
    current = plist->head;
    if (!(current)) return; 
    if ( current->value == value ){
        if (!(current->next)){
            plist->head = NULL; plist->tail = NULL;
        }
        else { 
            plist->head = current->next;
            free(current);
        }
    }
    else {
        while(current->next){
            if(current->next->value==value){
                if ((current->next)->next){ 
                    temp = current->next;
                    current->next = (current->next)->next;
                    free(temp);
                }
                else{
                    temp = current->next;
                    plist->tail = current;      
                    current->next = NULL;
                    free(temp);
                    break;
                }
            }
        current = current->next;    
        }
    }
} 


Node current current->next
0 0x9f39018 0x9f39028
1 0x9f39028 0x9f39038
2 0x9f39038 0x9f39048
3 0x9f39048 0x9f39058
4 0x9f39058 0x9f39068
5 0x9f39068 0x9f39078
6 0x9f39078 0x9f39088
7 0x9f39088 0x9f39098
8 0x9f39098 0x9f390a8
9 0x9f390a8 (nil)

after remove(5)

0 0x9f39018 0x9f39028
1 0x9f39028 0x9f39038
2 0x9f39038 0x9f39048
3 0x9f39048 0x9f39058
4 0x9f39058 0x9f39078
6 0x9f39078 (nil)

This code: 这段代码:

if ((current->next)->next){  
    current->next = (current->next)->next; 
    free(current->next); 

frees the next node after you have already removed it from the list. 从列表中删除后,释放下一个节点。 In other words, you are freeing the wrong node. 换句话说,您正在释放错误的节点。

请注意,您更正后的代码也会在空列表中崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM