-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
43 lines (41 loc) · 1020 Bytes
/
index.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
/**
* Problem: https://leetcode.com/problems/insertion-sort-list/description/
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
const { ListNode } = require('../util/javascript/problem-utils');
var insertionSortList = function (head) {
if (!head || !head.next) return head;
var result = new ListNode(null);
while (head) {
if (null === result.val) {
result = new ListNode(head.val);
} else {
if (head.val <= result.val) {
var tmp = new ListNode(head.val);
tmp.next = result;
result = tmp;
} else {
var tmp = result;
while (result.next && result.next.val < head.val) {
result = result.next;
}
var tmpNext = result.next;
result.next = new ListNode(head.val);
result.next.next = tmpNext;
result = tmp;
}
}
head = head.next;
}
return result;
};