Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
1 class Solution { 2 public: 3 ListNode *deleteDuplicates(ListNode *head) { 4 return deleteDuplicates_1(head); 5 } 6 7 ListNode *deleteDuplicates_1(ListNode *head) { 8 ListNode dummy(0), *cur = &dummy; 9 dummy.next = head; 10 while (cur->next) 11 { 12 ListNode *node = cur->next; 13 int val = node->val; 14 if (!node->next || node->next->val != val) { 15 cur = cur->next; 16 continue; 17 } 18 while (node && node->val == val) { 19 ListNode *del = node; 20 node = node->next; 21 delete del; 22 } 23 cur->next = node; 24 } 25 return dummy.next; 26 } 27 28 ListNode *deleteDuplicates_2(ListNode *head) { 29 if (!head) return NULL; 30 if (!head->next || head->val != head->next->val) { 31 head->next = deleteDuplicates(head->next); 32 return head; 33 } 34 int val = head->val; 35 while(head && head->val == val) { 36 ListNode *del = head; 37 head = head->next; 38 delete del; 39 } 40 return deleteDuplicates(head); 41 } 42 };