代码之家  ›  专栏  ›  技术社区  ›  matcheek

C节点删除问题中的单链表

  •  1
  • matcheek  · 技术社区  · 14 年前

    我在C语言中实现了一个单独的链表,并一直使用remove node函数。 它删除元素,链接它的两个邻居,但是下面的节点将下一个节点地址设置为空。为什么? 有人能帮忙吗?

      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)
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   MSN    14 年前

    此代码:

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

    从列表中删除下一个节点后释放该节点。换句话说,您释放了错误的节点。

        2
  •  1
  •   buddhabrot    14 年前

    请注意,您更正的代码也将崩溃在一个空列表上。