题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(!head) return nullptr;
ListNode *pre, *cur;
int rec = INT_MIN; //for recording the duplicate num
ListNode* newHead = new ListNode(INT_MIN); //the node for convenient traversal
newHead->next = head;
pre = newHead;
cur = head;
while(cur && cur->next)
{
ListNode* next = cur->next;
if(cur->val == next->val)
{
rec = cur->val;
while(cur && cur->val == rec)
{
delete(cur);
cur = next;
if(next) next = next->next;
}
pre->next = cur;
}
else{
pre = cur;
cur = cur->next;
}
}
cur = newHead->next;
delete(newHead); // avoid memory leak
return cur;
}
};