使用指针从单向链表中删除项目 [英] Using pointers to remove item from singly-linked list

查看:33
本文介绍了使用指针从单向链表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的 Slashdot 采访中 Linus Torvalds 举了一个例子,说明有些人如何以一种表明他们并不真正理解如何正确使用指针的方式使用指针.

不幸的是,由于我是他所说的人之一,我也未能理解他的例子:

<块引用>

我见过太多人通过跟踪prev"条目删除单链表条目,然后删除条目,这样做类似的东西

if (prev)上一个->下一个=条目->下一个;别的list_head = entry->next;

每当我看到这样的代码时,我就会说这个人不理解指针".可悲的是,这很常见.理解指针只是使用指向入口指针的指针",并且用 list_head 的地址初始化它.然后当他们遍历列表,他们可以删除条目而不使用任何条件,只要做

*pp = entry->next

有人能解释一下为什么这种方法更好,以及它如何在没有条件语句的情况下工作吗?

解决方案

一开始,你做

pp = &list_head;

并且,当你遍历列表时,你用

推进这个光标"

pp = &(*pp)->next;

通过这种方式,您可以始终跟踪您来自"的位置,并可以修改位于那里的指针.

所以当你找到要删除的条目时,你可以这样做

*pp = entry->next

通过这种方式,您可以处理 Afaq 在另一个答案中提到的所有 3 种情况,有效地消除了对 prevNULL 检查.

In a recent Slashdot Interview Linus Torvalds gave an example of how some people use pointers in a way that indicates they don't really understand how to use them correctly.

Unfortunately, since I'm one of the people he's talking about, I also failed to understand his example:

I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like

if (prev)
    prev->next = entry->next;
else
    list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common. People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing

*pp = entry->next

Can someone provide a bit more explanation about why this approach is better, and how it can work without a conditional statement?

解决方案

At the beginning, you do

pp = &list_head;

and, as you traverse the list, you advance this "cursor" with

pp = &(*pp)->next;

This way, you always keep track of the point where "you come from" and can modify the pointer living there.

So when you find the entry to be deleted, you can just do

*pp = entry->next

This way, you take care of all 3 cases Afaq mentions in another answer, effectively eliminating the NULL check on prev.

这篇关于使用指针从单向链表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆