开发者

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. It removes the element, links two of its neighbours, but the following node gets the next node address set to 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);
        }
    }
    els开发者_JS百科e {
        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.


Note that your corrected code will also crash on an empty list..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜