原題:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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
.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL) return NULL;
if(head->next==NULL) return head;
ListNode *tmp = head, *pre;
pre = NULL;
while(tmp){
if (tmp->val==tmp->next->val) {
ListNode *s = tmp->next;
while (s->next!=NULL && s->val==s->next->val){
s = s->next;
}
if(pre==NULL){
if(s->next!=NULL){
head = s->next;
tmp = head;
}
else return NULL;
}
else{
pre->next = s->next;
tmp = pre->next;
}
}
else {
pre = tmp;
tmp = tmp->next;
}
if (tmp==NULL || tmp->next==NULL) break;
}
return head;
}
};
需要注意的特殊情況:
1. {1}
2. {1->2}
3. {1->1->2}
要注意pre的初始值!NULL最佳,本次情況下不適合用head作爲初始值。