题解 | 删除有序链表中重复的元素-II 空间复杂度o(1)注意边界条件
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(head==nullptr||head->next==nullptr)return head;
ListNode* dommy=new ListNode(0);
dommy->next=head;
ListNode* differentpre=dommy;//不要忘记这一句
ListNode* samepre=head;
int value=head->val;
while(samepre&&samepre->next){
ListNode* cur=samepre->next;
if(cur->val!=value){
differentpre=samepre;
samepre=cur;
value=samepre->val;
}
//注意一种情况 最后几个是相同的元素
else{
while(cur&&cur->val==value){
samepre=cur;
cur=cur->next;
}
samepre=samepre->next;
value=samepre->val;
differentpre->next=samepre;
}
}
return dommy->next;
}
};
查看7道真题和解析
