gpt4 book ai didi

c++ - 删除 LinkedList 中的前面元素会产生垃圾

转载 作者:行者123 更新时间:2023-11-28 05:57:14 25 4
gpt4 key购买 nike

这是代码:

void deleteNodebyValue(struct Node *head, int data){
Node *cur = head;
Node *prevNode = head;
while(cur){

if(cur->data == data){
//cout << "if(cur->data == data)" << endl;
if(cur == head){
cout <<"if(cur == head)" << endl;
//head = cur->next;
return;

} else{
prevNode->next = cur->next;

}

delete cur;
return;

}

prevNode = cur;
cur = cur->next;
}
}

它适用于除前端(第一个/头)节点之外的任何节点。如果我尝试删除第一个节点,它会产生垃圾 :(。

最佳答案

您尝试修改函数中head 指向的位置,问题是您传递head 按值 这意味着指针是已复制,并且在函数中您只能在本地修改拷贝。您需要通过引用传递 head 指针:

void deleteNodebyValue(struct Node *&head, int data){...}

那当然不能直接return了,还是要真正删除节点。

关于c++ - 删除 LinkedList 中的前面元素会产生垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33913954/

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