Insertion Sort List LeetCode solution in JavaScript

1
/**
2
* Definition for singly-linked list.
3
* function ListNode(val, next) {
4
* this.val = (val===undefined ? 0 : val)
5
* this.next = (next===undefined ? null : next)
6
* }
7
*/
8
/**
9
* @param {ListNode} head
10
* @return {ListNode}
11
*/
12
var insertionSortList = function (head) {
13
let ptr = head;
14

15
while (ptr.next !== null) {
16
if (ptr.val <= ptr.next.val) ptr = ptr.next;
17
else {
18
let temp = ptr.next;
19
ptr.next = ptr.next.next;
20

21
if (temp.val < head.val) {
22
temp.next = head;
23
head = temp;
24
} else {
25
let ptr2 = head;
26
while (ptr2.next != null && temp.val >= ptr2.next.val) {
27
ptr2 = ptr2.next;
28
}
29
temp.next = ptr2.next;
30
ptr2.next = temp;
31
}
32
}
33
}
34
return head;
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0