可以比较下二种方法实现的差异,你更喜欢哪种呢?
方法一:
- typedef struct node
- {
- struct node * next;
- ....
- } node;
- typedef bool (* remove_fn)(node const * v);
- // Remove all nodes from the supplied list for which the
- // supplied remove function returns true.
- // Returns the new head of the list.
- node * remove_if(node * head, remove_fn rm)
- {
- for (node * prev = NULL, * curr = head; curr != NULL; )
- {
- node * next = curr->next;
- if (rm(curr))
- {
- if (prev)
- prev->next = curr->next;
- else
- head = curr->next;
- free(curr);
- }
- else
- prev = curr;
- curr = next;
- }
- return head;
- }
方法二:
- void remove_if(node ** head, remove_fn rm)
- {
- for (node** curr = head; *curr; )
- {
- node * entry = *curr;
- if (rm(entry))
- {
- *curr = entry->next;
- free(entry);
- }
- else
- curr = &entry->next;
- }
- }