[英]Error in Linked List Implementation
The following is an excerpt from the code to a singly linked list implementation from Data Structures and Algorithms in C++ (2nd Edition) by Adam Drozdek that involves deleting a node with a given value. 以下是摘自亚当·德罗兹德克(Adam Drozdek )的C ++数据结构和算法(第二版)中的代码到单链列表实现的摘录,其中涉及删除具有给定值的节点。
IntNode *tmp = head->next;
head = head->next;
delete tmp;
( head is defined elsewhere as an IntNode*) Are there typos in this code fragment, or is my mental processor incorrect in that head will always be a null pointer after every execution of the above code fragment? (在其他地方将head定义为IntNode *)此代码片段中是否有错别字,还是我的思维处理器不正确,因为在每次执行上述代码片段之后head总是为空指针?
不,它将指向列表的第二个元素(现在是第一个)。
When you write delete tmp
, you are deleting the object pointed to by tmp
. 当你写
delete tmp
,要删除的对象的指向tmp
。 However, after deleting head
will still point to the same place. 但是,删除后
head
仍将指向同一位置。 Dereferencing it ( *head
) will cause problems, because the object head
is pointing to has been deleted. 取消引用它(
*head
)会导致问题,因为对象head
指向的对象已被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.