从C中的双向链接列表中删除节点

时间:2013-08-29 11:28:54

标签: c logic doubly-linked-list

整体而言,我的程序用于在已排序的双向链表中插入和删除节点。插入工作和删除链表中的第一个节点工作正常,但删除最后一个节点。此外,删除中间和结尾的节点不起作用。如果我尝试删除最后一个节点,我会回到main();如果我尝试删除中间的节点,程序将崩溃。非常感谢您的帮助!

void remove(int n){
    struct node* help = head;
    if(head->data == n){
        if (head->next)
            help->next->prev = NULL;
        head = help->next;
    } else{
        while(help){
            if(help->data == n){
                if(help->next)
                    help->next->prev = help->prev;
                help->prev->next = help->next;
            } else help = help->next;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

help为真时,您可以中断while循环或将if(help->data ==n指针更新为下一项。

这样的东西
    //your code
    ...
    while(help){
        if(help->data == n){
            if(help->next)
                help->next->prev = help->prev;
            help->prev->next = help->next;
            //if you don't want to remove all nodes that have data 'n'
            break;
        } 
        //if you want to remove all nodes that have data 'n' remove else. 
        //but keep help = help->next
        else 
           help = help->next;

    ...
     //your code