-
Notifications
You must be signed in to change notification settings - Fork 30
/
insertion-sort-list.js
46 lines (42 loc) · 1.09 KB
/
insertion-sort-list.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
// Sort a linked list using insertion sort.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insetList = function (sortedList, item) {
if (!sortedList) return null;
var fakeHead = new ListNode(-1);
fakeHead.next = sortedList;
sortedList = fakeHead;
while (sortedList.next) {
if (item.val < sortedList.next.val) {
item.next = sortedList.next;
sortedList.next = item;
return fakeHead.next;
}
sortedList = sortedList.next;
}
sortedList.next = item;
return fakeHead.next;
}
var insertionSortList = function(head) {
if (!head || !head.next) return head;
var sorted = head;
var result = sorted;
var unsorted = head.next;
sorted.next = null;
while (unsorted) {
var temp = unsorted.next;
unsorted.next = null;
sorted = insetList(sorted, unsorted);
unsorted = temp;
}
return sorted;
};