0%

Javascript(leetcode#82) Remove Duplicates from Sorted List II

Difficult:Medium

題目

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:
example

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

Example 2:
example

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

解題思路

1.設當前及上一個node和存放開頭的變數
2.當遇到相同值時,依序往前比較
3.如pre還是空時,將開頭直接等於next

Solution

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
var deleteDuplicates = function (head) {
if (head == null) {
return head;
}
let cur = head;
let headnode = head;
let pre = null;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
let next = cur.next;
while (next != null && next.val == cur.val) {
next = next.next;
}
if (pre == null) {
headnode = next;
cur = next;
} else {
pre.next = next;
cur = next;
}
} else {
pre = cur;
cur = cur.next;
}
}
return headnode;
};