题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-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) return nullptr;
// 在链表前加一个表头
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* cur = dummy;
while(cur->next && cur->next->next) {
// 遇到相邻两个节点值相同
if(cur->next->val == cur->next->next->val) {
int tmp = cur->next->val;
// 将所有相同的都跳过
while(cur->next && cur->next->val == tmp) {
cur->next = cur->next->next;
}
}else{
cur = cur->next;
}
}
// 返回时去掉表头
return dummy->next;
}
};
曼迪匹艾公司福利 121人发布

