/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*本题与Remove Duplicates from Sorted List相似,只不过需要删除所有
重复元素。*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == nullptr) return head;
ListNode newHead(-1);
newHead.next = head;
ListNode *pre = &newHead, *cur = head, *next = cur->next;
if(next == nullptr) return head;
while(next != nullptr){
if(next->val == cur->val){//删除重复的所有元素
while(next != nullptr && next->val == cur->val) next = next->next;
while(cur != next){
ListNode *tmp = cur;
pre->next = cur->next;
cur = cur->next;
delete tmp;
}
if(cur == nullptr) break;
else next = cur->next;
}
else{
pre = pre->next;
cur = cur->next;
next = next->next;
}
}
return newHead.next;
}
};
09-27
09-27