TED《Linux操作系统之父》里提到的代码优化
今天老师放了这个TED的视频给我们看,里面提到了两个代码的比较,课上的时候没办法细看代码,只看到Linus Torvalds说前一段代码需要用到if判断是否是第一个节点,还是中间节点,而后一个代码就不需要。当时很好奇具体代码是什么样的,所以回来找到了这个视频,后面发现后一个代码是用上了指针,所以可以不需要判断,统一处理。代码如下,感兴趣的可以看看。
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(!prev)
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 entry we want to remove
while((*indirect) !=entry)
indirect=&(*indirect)->next;
//..and just remove it
*indirect=entry->next;
}
其实这就是数据结构里面的“哨兵”,我们要往链表中插入一个节点是这么做的
new_node->next = p->next;
p->next = new_node;
但是如果p指向一个null链表,这个就不适用了。因为p->next会报错。所以我们需要一个哨兵,我们把哨兵叫做节点prev,prev指向p;我们在prev的后面插入一个节点就变成了
new_node->next = prev->next;
prev->next = new_node;
这样解决了给空链表插入的问题,用这么一段代码解决了所有情况。