Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
题意
如果链表中有一个数重复了,去掉所有这个数
题解
1 class Solution { 2 public: 3 ListNode* deleteDuplicates(ListNode* head) { 4 ListNode*last = head, *p = head, *ans = new ListNode(0), *now = ans; 5 if (!p||p->next==NULL)return head; 6 p = p->next; 7 bool flag = false; 8 while (p) { 9 if (last->val != p->val) { 10 if (flag == false) { 11 now->next = last; now = now->next; 12 last = p, p = p->next; 13 } 14 else 15 last = last->next, p = p->next; 16 flag = false; 17 } 18 else { 19 flag = true; 20 last = last->next, p = p->next; 21 } 22 } 23 if(flag) 24 now->next = NULL; 25 else now->next = last; 26 return ans->next; 27 } 28 };