这里是我的代码: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;
}
标志着我在这我无法具体的线路((试图从中间删除一个节点时,下一个不为空时))。我尝试过该块的多种变体,但仍然没有任何变化。
所有帮助非常感谢!
您需要将'trail'初始化为'NULL'并处理头部被删除的情况。 – 2014-12-02 00:41:08