2014-12-02 52 views
1

这里是我的代码:C++:删除单链表中间的节点?

template<class L> 
Node<L>* LinkedList<L>::DeleteNode(L toDelete) 
{ 
     Node<L>* current; 
     Node<L>* trail; 

     if(head == NULL) 
     { 
       cout << "\n\nCannot delete from an empty list.\n\n"; 
     } 
     else 
     { 
      if(head->next == NULL) 
      { 
       if(head->data == toDelete) 
       { 
        current = head; 
        delete current; 
        head = current; 
        tail = current; 
        cout << "\nObject found. The list is now empty.\n"; 
       } 
       else 
       { 
        cout << "\nObject not found.\n"; 
       } 
      } 
      else 
      { 
       current = head; 

       while(current->data != toDelete && current->next != NULL) 
       { 
         trail = current; 
         current = current->next; 
       } 

       if(current->data == toDelete) 
       { 
        if(current->next == NULL) 
        { 
         trail->next = NULL; 
         current = trail; 
        } 
        else 
        { 
         // having error here 
         trail->next = current->next; 
         current = trail; 
         delete trail; 

        } 

        cout << "\nNode found and deleted.\n"; 
       } 
       else 
       { 
        cout << "\nObject not found.\n"; 
       } 
      } 
     } 

     return head; 
} 

标志着我在这我无法具体的线路((试图从中间删除一个节点时,下一个不为空时))。我尝试过该块的多种变体,但仍然没有任何变化。

所有帮助非常感谢!

+0

您需要将'trail'初始化为'NULL'并处理头部被删除的情况。 – 2014-12-02 00:41:08

回答

0

你只是简单地在这个阶段删除了错误的节点: 路径持有应该删除的节点的最后一个节点。 试试这个:

{ 
trail->next = current->next; 
delete current; 
//you may want to add: current=trail->next; if you are planing to keep working with 
// the rest of the list 
} 

您也应该检查你的代码块preior这样:

if(current->next == NULL) 
      { 
       trail->next = NULL; 
       current = trail; 
      } 

你actualy不delting这里enything,它真的应该是:

if((current->next == NULL) 
{ 
    trail->next = NULL; 
    delete current; 
} 
0

看起来你正在分配当前地址的地址,与追踪点相同,然后释放该资源,我认为这并不是意图。

现在你实际上是在分裂您的列表,你重新分配电流,使其指向落后删除线索(当你想要一种基于while循环点,以释放电流,要删除什么的)前右

它更有意义:

trail->next = current->next; delete current;

我不知道你怎么其他情况下按预期工作...代码看起来很滑稽我。例如,对于列表的结尾,你并没有释放任何资源(但你只是删除了一些资源,为什么没有资源被释放?)在删除头的情况下,你已经失去了你的列表并用您当前的实现创建了内存泄漏。

所有这一切 - 这是一个很好的开始,但我会退后一步,为您的链接列表应该提供的接口创建原型,并列出可能的边界案例(如删除头部) 。