-
Notifications
You must be signed in to change notification settings - Fork 20
/
RemoveDuplicatesFromSortedList.js
100 lines (89 loc) · 2.31 KB
/
RemoveDuplicatesFromSortedList.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/**
* 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.
*
* Accepted.
*/
function ListNode(val) {
this.val = val;
this.next = null;
this.equals = function (node) {
return this.next == null && node.next == null || this.val === node.val && (this.next != null) && this.next.equals(node.next);
}
}
/**
* @param {ListNode} head
* @return {ListNode}
*/
let deleteDuplicates = function (head) {
let node = head;
while (node != null && node.next != null) {
if (node.val === node.next.val) {
let tmp = node.next;
node.next = tmp.next;
tmp.next = null;
} else {
node = node.next;
}
}
return head;
};
if (deleteDuplicates(null) == null) {
console.log("pass")
} else {
console.error("failed")
}
let node112 = new ListNode(1);
node112.next = new ListNode(1);
node112.next.next = new ListNode(2);
let tmp = new ListNode(1);
tmp.next = new ListNode(2);
if (deleteDuplicates(node112).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}
let node11233 = new ListNode(1);
node11233.next = new ListNode(1);
node11233.next.next = new ListNode(2);
node11233.next.next.next = new ListNode(3);
node11233.next.next.next.next = new ListNode(3);
tmp = new ListNode(1);
tmp.next = new ListNode(2);
tmp.next.next = new ListNode(3);
if (deleteDuplicates(node11233).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}
let node111 = new ListNode(1);
node111.next = new ListNode(1);
node111.next.next = new ListNode(1);
tmp = new ListNode(1);
if (deleteDuplicates(node111).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}
let node1222 = new ListNode(1);
node1222.next = new ListNode(2);
node1222.next.next = new ListNode(2);
node1222.next.next.next = new ListNode(2);
tmp.next = new ListNode(2);
if (deleteDuplicates(node1222).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}
let node1122 = new ListNode(1);
node1122.next = new ListNode(1);
node1122.next = new ListNode(2);
node1122.next.next = new ListNode(2);
if (deleteDuplicates(node1122).equals(tmp)) {
console.log("pass")
} else {
console.error("failed")
}