Problem
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5
, return 1->2->5
.Given
1->1->1->2->3
, return 2->3
.Code
ListNode *deleteDuplicates(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(!head) return head; ListNode *prev = head; ListNode *curr = head; while(1){ ListNode *tmp = curr; while(curr && tmp->val == curr->val) curr = curr->next; if(head == tmp && tmp->next != curr) head = curr; prev->next = curr; if(!curr) break; if(!curr->next || curr->val != curr->next->val) prev= curr; } return head; }
No comments:
Post a Comment