gpt4 book ai didi

c++ - Deleting Element from linked list, interviews exposed book bug?

转载 作者:太空狗 更新时间:2023-10-29 23:53:04 26 4
gpt4 key购买 nike

页。 Programming interviews exposed book的29有如下示例代码,用于从链表中删除一个元素:

bool deleteElement(IntElement **head, IntElement *deleteMe)
{

IntElement *elem = *head;

if(deleteMe == *head){ /*special case for head*/
*head = elem->next;
delete deleteMe;
return true;
}

while (elem){
if(elem->next == deleteMe){
/*elem is element preceding deleteMe */
elem->next = deleteMe->next;
delete deleteMe;
return true;
}
elem = elem->next;
}

/*deleteMe not found */
return false;
}

我的问题是关于语句“delete deleteMe”,这是否实现了我们想要的效果,即实际删除该位置的元素,还是只是删除指向 deleteMe 元素的指针的拷贝?

最佳答案

delete deleteMe; 调用元素的析构函数并释放其关联的内存。这段代码是 C++,顺便说一句。

其余代码会更改数据结构列表,以取消该元素与其相邻元素的链接。

关于c++ - Deleting Element from linked list, interviews exposed book bug?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720112/

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