leetcode这里链表都没有头结点,因此在处理只有一个节点的链表会出问题。
因此需要新增头结点会非常方便操作。
ListNode dummy(-1); dummy.next = head; ListNode *prev = &dummy; // ... return dummy.next;
ListNode *dummy = new ListNode(-1); ListNode *prev = dummy; dummy->next = head; // ... return dummy->next;
这里务必要转载Linus大神的文章。
Linus:利用二级指针删除单向链表
http://blogread.cn/it/article/6243
上面文章的详解:Two star programming
http://wordaligned.org/articles/two-star-programming
if (prev) prev->next = entry->next; else list_head = entry->next;
这种情况在删除链表倒数第n个节点刚好出现。
当删除的节点是头结点的时候返回的就是head->next;
但是这里可以使用更好的方式,二级指针。
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 * const next = curr->next; 17 if (rm(curr)) 18 { 19 if (prev) 20 prev->next = next; 21 else 22 head = next; 23 free(curr); 24 } 25 else 26 prev = curr; 27 curr = next; 28 } 29 return head; 30 }
Two star programming
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 }