我的程序仍然从输入的数据文件中编译和打印。但是,在打印完所有内容后仍然会出现错误,因此程序没有干净地结束。
我在程序的这一部分得到了错误
while (current->next != tail)
基本上这个程序是使用链表来存储信息并将其输出到屏幕上。我的特别错误是使用clear()函数,该函数应该使用pop_back()函数清除整个链表。
//removes the last object from the linked list – deallocates memory
template <typename T>
void LL<T>::pop_back()
{
if(count==0)
{
//Do nothing. Nothing to remove.
return;
}
else{
Node<T> *current;
current=head;
while (current->next != tail)
{
current=current->next;
}
delete tail;
tail=current;
count--;
}
}
//Clears the linked list
template <typename T>
void LL<T>::clear()
{
Node<T> *current= head;
while (current != NULL)
{
pop_back();
//current=tail;
}
current=tail;
head=tail=NULL;
}
你的pop_back方法不能处理尾部和头部是同一元素的情况(也就是1个元素的链表)。作为权宜之计也许是给那个案子额外的支票?
if(count==0)
{
//Do nothing. Nothing to remove.
return;
}
else if (count==1)
{
head = tail = NULL;
count--;
return;
}
这个循环也是无限的,如下所示:
while (current != NULL)
{
pop_back();
//current=tail;
}
可能是while (head != NULL)
还是while (count != 0)
?
需要在被删除节点之前更新节点。以下是pop_back()
方法的简化版本:
template <typename T>
void LL<T>::pop_back()
{
Node<T> curr = head;
Node<T> prev = NULL;
while(curr != NULL && curr->next != NULL) // I'm assuming your tail's value is NULL
{
prev = curr;
curr = curr->next;
}
if(curr != NULL)
{
if(prev != NULL)
prev->next = NULL;
delete curr;
--count;
if(count == 0)
head = NULL;
}
}
我没有编译代码,但我认为我的想法很清楚。
顺便说一句,你可以提高clear()
方法的性能:
Node<T> curr = head;
while(curr != NULL)
{
Node<T> tmp = curr->next;
delete curr;
curr = tmp;
}
head = NULL;
tail = NULL;
count = 0;