gpt4 book ai didi

C++从后面删除节点——单链表

转载 作者:行者123 更新时间:2023-11-28 02:12:12 30 4
gpt4 key购买 nike

为什么我的代码不删除链表的最后一个元素?我创建了一个当前指针来横向穿过我的列表并跳出循环..(下一个是我的结构中名为 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;
}

最佳答案

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;

关于C++从后面删除节点——单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35263132/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com