我的链表中的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";
}
最佳答案
我猜这是一个单链接列表(也就是说,它只会前进),因为您没有上一个指针。考虑到这一点:
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;
}