-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path147.js
37 lines (33 loc) · 884 Bytes
/
147.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
const {
getArrayFromList,
getListFromArray,
ListNode,
} = require("./utils/list");
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insertionSortList = function (head) {
if (head === null) return null;
var lastSorted = head;
var current = head.next;
var result = new ListNode(0, head);
while (current) {
if (lastSorted.val <= current.val) {
lastSorted = lastSorted.next;
} else {
lastSorted.next = current.next;
var preNode = result;
while (preNode.next.val <= current.val) {
preNode = preNode.next;
}
current.next = preNode.next;
preNode.next = current;
}
current = lastSorted.next; // 每次指针指向已排好序的链表的next
}
return result.next;
};
const head = getListFromArray([1, 4, 2, 3]);
const result = insertionSortList(head);
console.log(getArrayFromList(result));