我的链接列表中的RemoveMid函数出现问题..代码似乎没问题,并且没有语法错误,但是当我调用此函数时,程序停止工作..我认为'这个函数的逻辑有问题。我希望你能帮助我纠正它。 这是RemoveMid函数的实现
template<typename T>
bool LinkedList<T>::RemoveMid(T& target)
{
Node<T> *current = new Node<T>;
bool found = false;
current = start;
while(current != NULL && !found)
{
if(current->next->info == target)
found = true;
if(!found)
current = current->next;
}
if(found)
{
Node<T> *Ptr;
Ptr = current->next;
current = current->next;
delete Ptr;
return true;
}
else
cout<<"target not found\n";
}
答案 0 :(得分:1)
我猜这是一个单一链接列表(也就是说,它只是前进)因为你没有Previous指针。考虑到这一点:
template<typename T> bool LinkedList<T>::Remove(T& target) // name changed as removing from anywhere in a linked list is effectively the same
{
Node<T>* current = start; // your allocation caused a memory leak here
Node<T>* previous = NULL;
bool found = false;
while(current != NULL)
{
if (current->info == target) // you should be looking at the current node, not the next node
{
found = true;
break;
}
previous = current;
current = current->next;
}
if (found)
{
if (previous == NULL) // deleting head node
{
start = current->next;
}
else
{
previous->next = current->next;
}
delete current;
}
else
{
cout<<"target not found\n";
}
return found;
}
答案 1 :(得分:1)
这是正常工作的版本(我认为;我没有测试过,而且根据我的经验,未经测试的软件是错误的),它似乎与原始意图类似(即,删除第一个元素时没有特殊情况):
template<typename T>
bool LinkedList<T>::RemoveMid(T const& target)
{
for (Node<T> **current(&this->start); *current; current = &(*current)->next) {
if ((*current)->info == target) {
std::auto_ptr<Node<T>> tmp(*current);
*current = (*current)->next;
return true;
}
}
std::cout<<"target not found\n";
return false;
}
答案 2 :(得分:0)
这段代码有很多个问题:
next
节点if(current->next->info == target)
这将遗漏您的start
节点。 new Node<T>
分配给current
指针,然后将start
重新分配给后两行。next
节点删除为您使用Ptr = current->next;
找到的节点,然后将delete Ptr
后两行删除。delete
的节点的指针!可能存在更多错误,但修复所有错误是一个良好的开端。
答案 3 :(得分:0)
我认为有几个地方我不明白
Node<T> *current = new Node<T>;
为什么要将新节点分配给当前节点,因为当前将分配当前的节点?
其次,
if(current->next->info == target)
found = true;
为什么使用current->next
代替current
? current->next
可能为NULL,导致current->next->info
无效。
BTW,你为什么不使用STL提供的链表?
答案 4 :(得分:0)
关于你的错误:
此作业current = current->next;
应为current->next = current->next->next;
因为如果删除当前节点之后的节点,则希望当前节点(current->next
)指向您删除的节点之后的节点(current->next->next
)
此外,代码可能存在一些问题。如果仍未找到节点并且current->next->info
为current->next
(NULL
指向最后一个元素),首先current
将导致程序崩溃,显然在这种情况下current->next->info
1}}是非法的。您也可以考虑在return false;
cout
答案 5 :(得分:-2)
这是您的代码的更好版本。减少变量和所有。试一试,看看它现在是否有效。 :)
template<typename T>
bool LinkedList<T>::RemoveMid(T& target)
{
Node<T> *current = new Node<T>;
current = start;
while(current != NULL)
{
if(current->next->info == target)
break; //stops while loop = faster since the whole list doesnt have to be parsed once we found the target
current = current->next;
}
if(current!=NULL)
{
current->next = current->next->next; //we "unlinked" target from the list and linked the rest of list instead
return true;
}
else
cout<<"target not found\n";
}