为什么我的代码不会删除链表的最后一个元素?我创建了一个当前指针,横向通过我的列表并突破循环..(接下来是我的结构中名为Card_Node的点)。回答应该很简单,只是不确定为什么它不会删除列表中的最后一个节点“
Card_Node *current;
current = front;
while ( current->next->next != NULL){
{
current = current-> next;
}
Card a = current->next->card;
return a;
delete current->next;
current->next = NULL;
}
答案 0 :(得分:1)
你以两种不同的方式检查NULL;这应该只进行一次。如果你考虑代码在你的代码中只有一个元素时所做的事情(在调试器或纸上通过它),那么你应该意识到问题所在。
答案 1 :(得分:1)
return current->next->card; // return !!
delete current->next; // so this will never be executed
current->next = NULL;
更新
如下面的评论要求进一步输入,这是一个更新,我试图保持原始原则。
if (front == nullptr) // Special handling of empty list
{
// Nothing to return - add error handling - throw exception perhaps
// or:
return ???; // A default card perhaps
}
if (front->next == nullptr) // Special handling of list with one element
{
// Only one element
Card a = front->card;
delete front;
front = nullptr;
return a;
}
Card_Node *current;
current = front;
while ( current->next->next != NULL) // Iterate to find last element
{
current = current-> next;
}
// Now current->next is last element, i.e. the one to remove
Card a = current->next->card;
delete current->next;
current->next = NULL;
return a;
答案 2 :(得分:0)
您的代码存在一些问题:
return
之前致电delete
,因此正在跳过delete
。while
循环中有一个太多的开括号。next
指针设置为NULL。front
设置为NULL。请改为尝试:
if (!front) {
// no cards in the list, do something...
return Card();
}
Card_Node *current = front;
Card_Node *previous = NULL;
while (current->next != NULL) {
previous = current;
current = current->next;
}
Card a = current->card;
delete current;
if (previous != NULL) {
previous->next = NULL;
}
if (front == current) {
front = NULL;
}