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
.
answer:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL) return head;
ListNode * start = head, * pre = head, * index = head;
int same = 0;
while(index != NULL){
if(index->val != start->val){
if(same > 1){
if(start == head) head = index;
else pre->next = index;
same = 1;
start = index;
}
else{
same = 1;
pre = start;
start = index;
}
}
else same ++;
index = index->next;
}
if(start == head && head->next != NULL) head = NULL;
if(same > 1) pre->next = NULL;
return head;
}
};