【问题标题】:Removing a Node from a Doubly Linked List in C从 C 中的双向链表中删除节点
【发布时间】:2013-09-01 19:34:06
【问题描述】:

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

【问题讨论】:

  • 使用调试器。在调试器中运行您的程序,当它崩溃时它会停止,然后您可以将调用堆栈遍历到您的代码。或者逐行浏览代码,看看它做了什么。
  • 哦,顺便说一句,一旦找到要删除的节点,您可能希望停止循环。可能还有free 那个节点。

标签: c logic doubly-linked-list


【解决方案1】:

if(help->data ==n 为真时,要么中断while 循环,要么更新help 指向下一项的指针。

类似

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

【讨论】:

  • 正常工作,但我无法删除列表中的第二个节点!
猜你喜欢
  • 2011-03-12
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多