82\. Remove Duplicates from Sorted List II

# 82. Remove Duplicates from Sorted List II (opens new window)

# Description

Difficulty: Medium

Related Topics: Linked List (opens new window), Two Pointers (opens new window)

Given the head of 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: head = [1,2,3,3,4,4,5]
Output: [1,2,5]
1
2

Example 2:

Input: head = [1,1,1,2,3]
Output: [2,3]
1
2

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

# Solution

Language: JavaScript

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function(head) {
    const dummy = new ListNode(0, head);
    let curr = dummy;
    
    while (curr.next?.next) {
        if (curr.next.val === curr.next.next.val) {
            const { val } = curr.next;
            while (curr.next?.val === val) 
                curr.next = curr.next.next;
        }       
        
        else curr = curr.next;
    }
    
    return dummy.next;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
上次更新: 2022/7/14 下午7:58:28