题目:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
思路:这个要求是把连续重复 value 节点全删掉,当遇到重复的就将指针更新,只有不重复了才链入最终结果。
递归:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) {
return head;
}
if (head->val != head->next->val) {
head->next = deleteDuplicates(head->next);
return head;
}
while (head && head->next && head->val == head->next->val) {
head = head->next;
}
return deleteDuplicates(head->next);
}
};
非递归:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode * res = new ListNode(), *pre = res;
while (head) {
ListNode *tmp = head->next;
bool is_duplicate = false;
while (tmp && head->val == tmp->val) {
tmp = tmp->next;
is_duplicate = true;
}
if (!is_duplicate) {
pre->next = head;
pre = head;
}
head = tmp;
}
pre->next = nullptr;
return res->next;
}
};