-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path82_javascript.js
62 lines (58 loc) · 1.2 KB
/
82_javascript.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
// 示例 1:
// 输入: 1->2->3->3->4->4->5
// 输出: 1->2->5
// 示例 2:
// 输入: 1->1->1->2->3
// 输出: 2->3
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// 双指针
var deleteDuplicates = function (head) {
if (!head || !head.next) {
return head;
}
// 设定 temp
let temp = new ListNode();
temp.next = head;
p = temp;
let q = head;
while (q && q.next) {
if (p.next.val == q.next.val) {
while (q.next && p.next.val == q.next.val) {
q = q.next;
}
p.next = q.next;
q = q.next;
} else {
q = q.next;
p = p.next;
}
}
return temp.next;
};
// 递归
var deleteDuplicates = function (head) {
if (!head || !head.next) {
return head;
}
let next = head.next;
if (head.val == next.val) {
while (next && head.val == next.val) {
next = next.next;
}
head = deleteDuplicates(next);
} else {
head.next = deleteDuplicates(next);
}
return head;
};