思想:
注意使用头结点来简化编程;
删除的节点要delete,避免内存泄露;
/**
* 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 || head->next == NULL) return head;
ListNode dummy(0);
dummy.next = head;
ListNode *prev = &dummy;
ListNode *cur = head;
while(cur != NULL) {
bool dup = false;
while(cur->next != NULL && cur->val == cur->next->val) {
dup =true;
ListNode *tmp = cur;
cur = cur->next;
delete tmp;//necessary, else memory leak
}
if(dup) {
ListNode *tmp = cur;
cur = cur->next;
delete tmp;
continue;
}
prev->next = cur;
prev = prev->next;
cur = cur->next;
}
prev->next = cur;
return dummy.next;
}
};