82. Remove Duplicates from Sorted List II

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* slow = new ListNode(-101), *ret = slow;
slow->next = head;
while(slow->next){
ListNode * fast = slow->next;
while(fast->next && fast->next->val ==fast->val ) {
fast=fast->next;
}
if(slow->next ==fast) slow=slow->next;
else slow->next = fast->next;
}
return ret->next;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)