82. Remove Duplicates from Sorted List II
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Solution {public : ListNode* deleteDuplicates (ListNode* head) { if (!head or !head->next) return head; while (head and head->next and head->val == head->next->val) { int v = head->val; while (head && head->val == v) head = head->next; } if (head) { head->next = deleteDuplicates (head->next); } return head; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution {public : ListNode* deleteDuplicates (ListNode* head) { ListNode* tmp = new ListNode (0 , head); ListNode* prev = tmp; while (head) { while (head and head->next and head->val == head->next->val) { int v = head->val; while (head && head->val == v) head = head->next; } prev->next = head; prev = head; if (head) head = head->next; } return tmp->next; } };