Removing a Node from a Doubly Linked List in C

风流意气都作罢 提交于 2019-12-14 03:07:39

问题


As a whole my program is for inserting and deleting nodes in a sorted doubly linked list. Insertion works and deleting the first node from the linked list works fine, except deleting the last node. Also, deleting nodes in the middle and end don't work. If I try to delete the last node, I am led back to main(); If I try deleting a node in the middle, the program crashes. Your help is appreciated!

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:


Either you break your while loop or update the help pointer to next item when if(help->data ==n is true.

Something like

    //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


来源:https://stackoverflow.com/questions/18509733/removing-a-node-from-a-doubly-linked-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!