本文源于对一段采访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
void remove_list_entry(list_node **head, list_node *entry)
{
list_node *prev = NULL;
list_node *walk = *head;
while (walk != entry) {
prev = walk;
walk = walk->next;
}
if (!prev) {
*head = entry->next;
} else {
prev->next = entry->next;
}
}
#endif
#ifdef QUALITY_EDITION
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);
list_node *new_node1 = new list_node;
new_node1->next = NULL;
new_node1->value = 100;
add_list_entry(&head, new_node1);
list_node *new_node2 = new list_node;
new_node2->next = NULL;
new_node2->value = 200;
add_list_entry(&head, new_node2);
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(包括我)写出是没品位版本吧。 大神一段代码,功力可见一斑。膜拜~~