/**
* 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 || !head->next)
return head;
ListNode* dummy=new ListNode(-1); //哑结点
dummy->next=head;
ListNode* slow=dummy,*fast=head;
while(fast && fast->next){
if(fast->val==fast->next->val){ //如果快指针与前一个元素重复
while(fast->next && fast->val==fast->next->val) //快指针一直向前移
fast=fast->next;
slow->next=fast->next;
fast=fast->next;
}
else{ //如果不重复,快慢指针都前移
slow=fast;
fast=fast->next;
}
}
return dummy->next;
}
};
82. 删除排序链表中的重复元素 II
最新推荐文章于 2023-01-17 07:00:00 发布