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

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

问题描述

在最近<一href=\"http://meta.slashdot.org/story/12/10/11/0030249/linus-torvalds-answers-your-questions\">Slashdot 采访Linus Torvalds公司给了一些人如何,表明他们并不真正了解如何正确使用它们的方式使用指针的例子。

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:

我见过太多的人谁通过保持preV进入轨道删除单链表条目,然后删除该条目,做这样的事情

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

,每当我看到code那样,我只是去此人不理解指针。而且它是可悲的是相当普遍。谁了解指针人们只使用一个指针项指针,并初始化与LIST_HEAD的地址。然后,他们遍历目录,就可以删除该条目不使用任何条件语句,只需执行

*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?

推荐答案

在开始的时候,你做

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 =入门&gt;接下来

这样,你采取的三种情况下护理的 AFAQ 的提到了另一个答案,有效地消除了 NULL 检查 $ p $光伏

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

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

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