题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
//保留原链表中只存在一次的元素结点 可能会删除头结点 所以做一个虚拟头结点
if(head == nullptr || head->next == nullptr) return head;
ListNode temp(-1);
temp.next = head;
ListNode* virhead = &temp;
ListNode* p = virhead;
//处理head链表
while(p->next != nullptr && p->next->next != nullptr)
{
//如果有相同元素
if(p->next->val == p->next->next->val)
{
//找出是不是相同元素的范围 p --- last 前开后闭区间
ListNode* last = p->next->next;
while(last->next != nullptr &&last->next->val == p->next->val)
{
last = last->next;
}
//删除这个区间
ListNode* del = p->next;
while(del != last)
{
p->next = del->next;
delete del;
del = p->next;
}
del = p->next;
p->next = del->next;
delete del;
continue;
}
p = p->next;
}
return virhead->next;
}
};
