-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertion-sort-list.js
45 lines (45 loc) · 1012 Bytes
/
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
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insertNode = function(head, node) {
if (!head) {
head = new ListNode(node.val)
return head
}
var current = head
var prev = new ListNode(0)
var newnode = new ListNode(node.val)
while(current) {
if(node.val <= current.val) {
if(current === head) {
prev.val = node.val
prev.next = current
head = prev
return head
}
newnode.next = current
prev.next = newnode
return head
}
prev = current
current = current.next
}
prev.next = newnode
return head
}
var insertionSortList = function(head) {
var result = null
while(head) {
result = insertNode(result, head)
head = head.next
}
return result
};