-
Notifications
You must be signed in to change notification settings - Fork 33
/
083-Remove-Duplicates-from-Sorted-List.js
69 lines (56 loc) · 1.13 KB
/
083-Remove-Duplicates-from-Sorted-List.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
63
64
65
66
/**
* https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
* Difficulty:Easy
*
* Given a sorted linked list, delete all duplicates such that each element appear only once.
*
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->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) {
var p = head;
if (!p) return p;
var all = [p.val];
var t = p.next;
while (t) {
if (all.indexOf(t.val) == -1) {
all.push(t.val);
p = t;
t = p.next;
} else {
t = t.next;
p.next = t;
}
}
return head;
};
/**
* 改进方案
*
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates2 = function (head) {
var p = head;
while (p && p.next) {
if (p.val == p.next.val) {
p.next = p.next.next;
} else {
p = p.next;
}
}
return head;
};