【问题标题】:How to delete node in double linked list correctly?如何正确删除双链表中的节点?
【发布时间】:2016-02-23 00:02:40
【问题描述】:
void SinglyLinkedList::removeBike(int c)
{
   Node* current = head;

   for(int i = 0; i < c; i++){         // traverse to desired node
       current = current -> next;
   } 

   if(current -> next != NULL && current -> prev != NULL){
        current -> prev -> next = current -> next;
        current -> next -> prev = current -> prev;
        delete current;                     //delete node
   }
   else if(current -> next == NULL){
      current -> prev -> next = current;
      delete current;
   }
   else if(current -> prev == NULL){
       current -> next -> prev = current;
       delete current;
   }    
   else 
       cout << "How did you make it this far?";

}

我很确定我在这里没有理解某些内容,但到目前为止研究并没有帮助。

从逻辑上讲,这对我来说是有道理的,但我觉得这太简单了,无法工作,但事实并非如此。

已编辑:更新代码减去输入检查,当我输入任何 int 时它会中断。我也应该将类重命名为双向链表......只是注意到了

【问题讨论】:

  • 我见过的找出链表的最好方法是在一张纸上画出节点,然后一步一步画出链接所需的所有变化。
  • for(int i = 0; i &lt; c; i++){ 应该是for(int i = 0; i &lt; c || current != NULL; i++){。
  • && current != NULL 对我来说效果更好......然后你必须弄清楚当你在循环之后以 NULL 电流结束时该怎么做。
  • @Josh 停止编辑您的问题并尝试修复代码。不要创建使当前答案无效的移动目标。这没用。
  • 它在第一个 if 语句的第一行打破了我。完成编辑。

标签: c++ list pointers nodes


【解决方案1】:

不,绝对没有那么简单。

首先,如果c 参数超过了列表的大小,你会因为你的current 指针碰到最后一个节点上的空指针,然后飞过它而导致空指针取消引用。

然后,如果 c 为 0 或列表的最后一个元素的索引,那么它要么是 prev 要么是 next 指针,相应地,将是空的,你也会因为空而爆炸指针取消引用。

current -> prev -> next = current -> next;
current -> next -> prev = current -> prev;

如果current 是列表中的第一个元素,current-&gt;prev 显然会为空。如果current 是列表中的最后一个元素,current-&gt;next 显然将为空。猜猜当您尝试取消引用空指针时会发生什么?

结论:

A) 检查函数的输入参数是否有效。

B) 当要删除的节点是双向链表中的第一个或最后一个节点时,提供特殊处理。

编辑:应大众要求,有人想知道我将如何解决这个问题:

void SinglyLinkedList::removeBike(int c)
{
   Node* current = head;

   for(int i = 0; i < c; i++){
       if (!current)
           break;
       current = current -> next;
   } 

   if (!current)
           return; // Or throw an exception. Or return a bool false, maybe.

   if (current->prev)
       current -> prev -> next = current -> next;
   else
       head=current->next;

   if (current->next)
       current -> next -> prev = current -> prev;
   else
       tail=current->prev;  // Assuming that there's a tail, somewhere around here...
   delete current;                      //delete node

   // Maybe "return true;" here...
}

【讨论】:

  • 啊不知道我是怎么搞砸的。甚至没有想到第一个或最后一个是想要的。哇。感谢您的意见!好吧,如果我在完成之后还有其他问题,我会进行编辑。
  • 不,不需要删除它。这是一个有效的问题。
  • @SamVarshavchik 一个完全固定的 SinglyLinkedList::removeBike() 函数的代码示例至少会很棒。
  • "应受欢迎的要求" 到目前为止,我不知道自己是一个如此受欢迎的人 :-P,但 THX。虽然一个挑剔的 // Maybe "return true;" here... 函数返回类型实际上是void。
  • @πάνταῥεῖ 我认为return true 是一个建议,您可以更改函数签名。我也同意,很高兴知道它是否已被删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多