-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
44 lines (38 loc) · 1.21 KB
/
res.ts
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
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function insertionSortList(head: ListNode | null): ListNode | null {
if (!head) {
return null;
}
const dumpyHead = new ListNode(0);
let lastSortedNode = head;
dumpyHead.next = head;
while (lastSortedNode?.next) {
const nextNode = lastSortedNode.next;
if (nextNode.val >= lastSortedNode.val) {
lastSortedNode = nextNode;
} else {
let currentIterateNode = dumpyHead;
while (currentIterateNode.next && currentIterateNode.next.val < nextNode.val) {
currentIterateNode = currentIterateNode.next;
}
// link
lastSortedNode.next = nextNode.next;
// swap
const swapNode = currentIterateNode.next;
currentIterateNode.next = nextNode;
nextNode.next = swapNode;
lastSortedNode = swapNode as ListNode;
}
}
return dumpyHead.next;
};