《对话Linus Torvalds:大多黑客甚至连指针都未理解》
http://www.csdn.net/article/2013-01-10/2813559-two-star-programming
“不懂指针”的开发者代码示例:
1 typedef struct node
2 {
3 struct node * next;
4 ....
5 } node;
6
7 typedef bool (* remove_fn)(node const * v);
8
9 // Remove all nodes from the supplied list for which the
10 // supplied remove function returns true.
11 // Returns the new head of the list.
12 node * remove_if(node * head, remove_fn rm)
13 {
14 for (node * prev = NULL, * curr = head; curr != NULL; )
15 {
16 node * next = curr->next;
17 if (rm(curr))
18 {
19 if (prev)
20 prev->next = curr->next;
21 else
22 head = curr->next;
23 free(curr);
24 }
25 else
26 prev = curr;
27 curr = next;
28 }
29 return head;
30 }
Linus Torvalds提供的解决方案:
1 void remove_if(node ** head, remove_fn rm)
2 {
3 for (node** curr = head; *curr; )
4 {
5 node * entry = *curr;
6 if (rm(entry))
7 {
8 *curr = entry->next;
9 free(entry);
10 }
11 else
12 curr = &entry->next;
13 }
14 }
时间: 2024-11-09 09:59:10