【发布时间】:2019-05-22 09:19:19
【问题描述】:
在一次关于 Linus Torvalds 的采访中,他分享了拥有“好品味”的重要性。他用以下代码解释了良好的品味。
带有“坏味道”的代码
remove_list_entry(entry)
{
prev = NULL;
walk = head;
// Walk the list
while (walk != entry) {
prev = walk;
walk = walk->next;
}
// Remove the entry by updating the head
// or the previous entry
if (!entry)
head = entry->next;
else
prev-next = entry->next;
}
带有“好品味”的代码
remove_list_entry(entry)
{
// The "indirect" pointer points to the
// *address* of the thing we'll update
indirect = &head;
// Walk the list, looking for the thing that
// points to the thing we want to remove
while ((*indirect) != entry)
indirect = &(*indirect)->next;
// .. and just remove it
*indirect = entry->next;
}
两个例子都没有使用free()来释放要删除的节点的内存。有人能告诉我为什么代码是这样写的吗?还是我对 C 或链表的概念有误?
【问题讨论】:
-
你能提供采访的链接/参考吗?
-
这取决于列表的总体设计。从列表中删除一个节点并不意味着该节点可能不再被使用。
-
抛开风格不谈,上面的例子不是坏了吗?
-
您可以在What is the pointer to pointer technique for the simpler traversal of linked lists? 找到一个关于指针到指针链表处理技术的问题,该问题作为An interesting C linked list idiom 的副本关闭。
-
@500-InternalServerError 两者都只是伪代码。我不希望它们中的任何一个是完整的。在真正的“好品味”示例中,
head可能不是全局变量。一些NULL检查也将包括在内。
标签: c linked-list