gpt4 book ai didi

c++ - 从链表中删除节点

转载 作者:行者123 更新时间:2023-11-28 00:31:53 25 4
gpt4 key购买 nike

我一直停留在这个从列表中删除节点的函数上,如果列表中有两个名字,它们都消失了。如果 Anne 和 John 在列表中,而我想删除 Anne,那么我的列表为空,John 消失了。

如果我删除节点初始化,我缺少什么来保持列表中的连接?

bool ContactList::remove(string key)
{
NodePtr prev = NULL;

for(NodePtr temp = head; temp != NULL; temp = temp->link)
{
if(temp->data.key == key)
{
if(prev == NULL)
{
head = temp->link;
delete temp;
return true;
}
else
{
prev = temp->link;
delete temp;
return true;
}

}

}
return false;
}

最佳答案

您没有在循环的每次迭代中都使 prev 保持最新。你想要这样的东西:

prev = temp;

for 循环的底部。

关于c++ - 从链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534142/

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