力扣82. 删除排序链表中的重复元素 II
单链表真的遭罪,不过有一个技巧,就是创建一个head,这样便于处理首元素就需要删除的情况。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* deleteDuplicates(ListNode* head) { 14 ListNode* thead = new ListNode(-10000, head); 15 ListNode* t = thead; 16 ListNode* s = thead; 17 ListNode* f = s->next; 18 bool flag = false; 19 20 while (f) { 21 if (s->val != f->val) { 22 if (flag) { 23 flag = false; 24 removeRange(t, f); 25 s = t;//->next; if (NULL != s) break; 26 f = s->next; 27 continue; 28 } 29 t = s; 30 s = s->next; 31 f = f->next; 32 } else { 33 flag = true; 34 f = f->next; 35 } 36 } 37 38 if (flag) 39 removeRange(t, NULL); 40 41 head = thead->next; 42 delete thead; 43 return head; 44 } 45 46 private: 47 void removeRange(ListNode* start, ListNode* end) 48 { 49 ListNode* t; 50 ListNode* d = start->next; 51 52 while (end != d) { 53 t = d->next; 54 delete d; 55 d = t; 56 } 57 58 start->next = end; 59 } 60 };