题解 | #删除有序链表中重复的元素-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) return nullptr;
auto dummy = new ListNode(-1), cur = dummy;
dummy->next = head;
while (cur->next && cur->next->next) {
if (cur->next->val == cur->next->next->val) {
auto temp = cur->next->val;
while (cur->next && cur->next->val == temp)
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
return dummy->next;
}
};
思路:与上一题的区别是删除所有出现次数大于1的节点,上一题保留一个出现次数大于1的节点
遍历cur的next节点,当cur的next节点值与cur的next的next节点值相等时,删除所有与cur的next节点值相同的节点
时间复杂度:O(n)
空间复杂度:O(1)
查看12道真题和解析