TED《Linux操作系统之父》里提到的代码优化

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;

这样解决了给空链表插入的问题,用这么一段代码解决了所有情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值