17

Linus Torvalds 在 TED 演讲上所说的有品味的代码

 2 years ago
source link: https://www.v2ex.com/t/854016
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  程序员

Linus Torvalds 在 TED 演讲上所说的有品味的代码

  Biwood · oodzchen · 3 小时 19 分钟前 · 963 次点击

需求是从单向链表中删除一个指定节点。

教科书上的(普通的)写法:

void remove_cs101(list *l, list_item *target)
{
        list_item *cur = l->head, *prev = NULL;
        while (cur != target) {
                prev = cur;
                cur = cur->next;
        }
        if (prev)
                prev->next = cur->next;
        else
                l->head = cur->next;
}

优雅的(有品味的)写法:

void remove_elegant(list *l, list_item *target)
{
        list_item **p = &l->head;
        while (*p != target)
                p = &(*p)->next;
        *p = target->next;
}

目测充分利用的指针的特性,代码量少了不少。

代码仓库和详细解释在这里: https://github.com/mkirchner/linked-list-good-taste/blob/main/README.md


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK