Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1773964

Browse files
author
zongyanqi
committed
add Easy_83_Remove_Duplicates_from_Sorted_List
1 parent b4d8d47 commit 1773964

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
*
3+
* Given a sorted linked list, delete all duplicates such that each element appear only once.
4+
*
5+
* For example,
6+
* Given 1->1->2, return 1->2.
7+
* Given 1->1->2->3->3, return 1->2->3.
8+
*
9+
*/
10+
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* function ListNode(val) {
15+
* this.val = val;
16+
* this.next = null;
17+
* }
18+
*/
19+
20+
/**
21+
* @param {ListNode} head
22+
* @return {ListNode}
23+
*/
24+
var deleteDuplicates = function (head) {
25+
26+
var p = head;
27+
if (!p) return p;
28+
var all = [p.val];
29+
var t = p.next;
30+
31+
while (t) {
32+
33+
if (all.indexOf(t.val) == -1) {
34+
all.push(t.val);
35+
p = t;
36+
t = p.next;
37+
} else {
38+
t = t.next;
39+
p.next = t;
40+
}
41+
}
42+
return head;
43+
44+
};
45+
46+
/**
47+
* 改进方案
48+
*
49+
* @param {ListNode} head
50+
* @return {ListNode}
51+
*/
52+
var deleteDuplicates2 = function (head) {
53+
54+
var p = head;
55+
while (p && p.next) {
56+
if (p.val == p.next.val) {
57+
p.next = p.next.next;
58+
} else {
59+
p = p.next;
60+
}
61+
}
62+
return head;
63+
64+
};
65+
66+
67+

0 commit comments

Comments
 (0)