82. Remove Duplicates from Sorted List II**

82. Remove Duplicates from Sorted List II**

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

Title Description

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Return the linked list sorted as well.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

C ++ implementation 1

Use [pre, next)to mark the value of the same node, if pre->next == next, description preis unique and should be added to dummythe list. Also a problem deleting duplicate nodes in the Linked List 206. The Reverse * .

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode* dummy = new ListNode(0);
        auto p = dummy;
        auto pre = head, next = head->next;
        auto value = pre->val;
        
        while (next) {
            if (next->val == value) {
                next = next->next;
            } else {
                if (pre->next == next) {
                    p->next = pre;
                    p = p->next;
                }
                pre = next;
                next = next->next;
                value = pre->val;
            }
        }
        p->next = pre->next ? nullptr : pre;
        
        head = dummy->next;
        return head;
    }
};
Published 455 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/Eric_1993/article/details/104987741