0

总的来说,我的程序用于在排序的双向链表中插入和删除节点。插入工作并从链表中删除第一个节点工作正常,除了删除最后一个节点。此外,删除中间和末尾的节点不起作用。如果我尝试删除最后一个节点,我会被引导回 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;
        }
    }
}
4

1 回答 1

1

要么你打破你的while循环,要么在为真help时更新指向下一项的指针。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
于 2013-08-29T11:39:26.003 回答