LeetCode-82. Remove Duplicates From Sorted List II

问题描述

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 :

img

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

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.

解答

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
28
29
30
31
32
33
34
35
36
/*
* @Description: 82. Remove Duplicates from Sorted List II
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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}
*/
const deleteDuplicates = function(head) {
let dummy = new ListNode()
dummy.next = head
let pre = dummy
let cur = head

while (cur !== null) {
while (cur.next !== null && cur.val === cur.next.val) {
cur = cur.next
}
// 判断是否有重复项
if (pre.next === cur) {
pre = cur
} else {
pre.next = cur.next
}
cur = cur.next
}
return dummy.next
}