-
Notifications
You must be signed in to change notification settings - Fork 20
/
InsertionSortList.js
57 lines (47 loc) · 1.01 KB
/
InsertionSortList.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
/**
* Sort a linked list using insertion sort.
*
* Accepted.
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param {ListNode} head
* @return {ListNode}
*/
let insertionSortList = function (head) {
let fakeHead = new ListNode(0);
while (head != null) {
let pre = fakeHead;
while (pre.next != null && pre.next.val <= head.val) {
pre = pre.next;
}
let headNext = head.next;
head.next = pre.next;
pre.next = head;
head = headNext;
}
return fakeHead.next;
};
if (insertionSortList(null) == null) {
console.log("pass")
} else {
console.error("failed")
}
/*
if (insertionSortList(new ListNode(1)) === new ListNode(1)) {
console.log("pass")
} else {
console.error("failed")
}
let node0 = new ListNode(1);
node0.next = new ListNode(0);
node1 = new ListNode(0);
node1.next = new ListNode(1);
if (insertionSortList(node0) === node1) {
console.log("pass")
} else {
console.error("failed")
}*/