82. Remove Duplicates from Sorted List II

2019/10/21 Leetcode

82. Remove Duplicates from Sorted List II

Tags: ‘Linked List’

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

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

Solution

Similar to 83, this time we need dummy node . Also when no duplicate, prev shouldn’t increment

//Better. no need for after pointer
public ListNode deleteDuplicates(ListNode head) {
        // need a dummy node this time for corner cases
        if (head == null || head.next == null) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy, curr = head;
        while (curr != null) {
            while (curr.next != null && curr.next.val == curr.val) {
                curr = curr.next;
            }
            
            if (prev.next == curr) { // no duplicate, increment both
                prev = prev.next;
            } else {
                prev.next = curr.next;
            }
            curr = curr.next;
        }
        return dummy.next;
    }
public ListNode deleteDuplicates(ListNode head) {
    // need a dummy node this time for corner cases
    if (head == null || head.next == null) return head;
    ListNode dummy = new ListNode(-1);
    dummy.next = head;
    ListNode prev = dummy, curr = head;
    while (curr != null) {
        ListNode after = curr.next;
        while (after != null && after.val == curr.val) {
            after = after.next;
        }
        if (curr.next == after) { // no duplicates, just increment both
            prev = prev.next;
            curr = curr.next;
        } else { // delete duplicate, and set curr to after
            prev.next = after;
            curr = after;
        }
    }
    return dummy.next;
}

Search

    Table of Contents