82. Remove Duplicates from Sorted List II
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.
/**
* 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) {
ListNode* dummyHead = new ListNode(-1);
dummyHead->next = head;
// pPre 作为重复段的前驱
ListNode* pPre = dummyHead;
ListNode* pCur = head;
while(pCur){
// 1.查找重复值出现的范围:
while(pCur->next && pPre->next->val == pCur->next->val)
pCur = pCur->next;
// 如果pPre->next和pCur是同一指针,则pPre->next元素没有重复出现,直接往右移动pPre
if(pPre->next == pCur)
pPre = pPre->next;
// 删除pPre->next 到 pCur 的所有节点
// 删除节点区间 [pPre->next, pCur] 左闭右闭
// 并连接pPre 与 pCur->next
else{
ListNode* temp = pPre->next;
pPre->next = pCur->next;
while(temp != pCur->next){
ListNode* delNode = temp;
temp = temp->next;
delete delNode;
}
}
pCur = pCur->next;
}
return dummyHead->next;
}
};