一段有品位的代码

本文源于对一段采访Linux之父的视频,其中李纳斯说的一段链表删除算法是否有品位,补全外围代码,体会大神的品位。看代码~

/**
 * 本文源于对一段采访Linux之父的视频,其中
 * 李纳斯说的一段链表删除算法是否有品位,
 * 补全外围代码,体会大神的品位。 
 */
#include <iostream>

#define QUALITY_EDITION 

struct list_node
{
    list_node *next;
    int value;  
};

void print_list(list_node **head)
{
    std::cout << " ------ content -------" << std::endl;
    list_node *current = *head;
    while (current != NULL) {
        std::cout << current->value << " ";
        current = current->next;
    }
    std::cout << std::endl;
}

void add_list_entry(list_node **head, list_node *new_node)
{
    list_node *tmp = *head;
    *head = new_node;
    new_node->next = tmp;
}

#ifndef QUALITY_EDITION
/**
 * 普通版本 即没品位版本
 * 
 * 普通版本使用一个if来判断删除的是否是头节点
 */ 
void remove_list_entry(list_node **head, list_node *entry)
{
    list_node *prev = NULL;
    list_node *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;
    }
}
#endif

#ifdef QUALITY_EDITION
/**
 * Linux 李纳斯 说的有品位的 list删除方法
 *
 * 此方法中没有使用if语句
 *
 * indirect 变量存储的是 <要删除节点> 的前一个节点
 * 的next字段的地址,指向第一个节点地址为head变量(相当与
 * 其他节点前一个节点next的地址),因此其他节点的处理是一致
 * 的,不需要特殊处理
 */  
void remove_list_entry(list_node **head, list_node *entry)
{
    list_node **indirect = head;
    while ((*indirect) != entry) {
        indirect = &(*indirect)->next;
    }
    *indirect = entry->next;
}
#endif

void init_list(list_node **head)
{
    *head = NULL;
}

int main(int argc, char **argv)
{
    list_node *head;
    init_list(&head);
    // add node 1 
    list_node *new_node1 = new list_node;
    new_node1->next  = NULL;
    new_node1->value = 100;
    add_list_entry(&head, new_node1);
    // add node 2
    list_node *new_node2 = new list_node;
    new_node2->next  = NULL;
    new_node2->value = 200;
    add_list_entry(&head, new_node2);
    // add node 3
    list_node *new_node3 = new list_node;
    new_node3->next  = NULL;
    new_node3->value = 300;
    add_list_entry(&head, new_node3);

    print_list(&head);

    remove_list_entry(&head, new_node2);
    print_list(&head);

    return 0;
}
两个版本区别在于是否单独考虑第一个节点的处理。
我想有不少coder(包括我)写出是没品位版本吧。 大神一段代码,功力可见一斑。膜拜~~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值