-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathNo147.insertion-sort-list.js
More file actions
103 lines (92 loc) · 1.99 KB
/
Copy pathNo147.insertion-sort-list.js
File metadata and controls
103 lines (92 loc) · 1.99 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* Difficulty:
* Medium
*
* Desc:
* Sort a linked list using insertion sort.
*
* 用插入排序的方法给链表排序
*/
/**
* 思路:
* 按照插入排序的思路即可。
* 按照顺序向后遍历,每次遇见乱序的节点,先将其从链表中去除,同时认为该节点之前的链表已经是顺序的,
* 最后遍历之前的链表,将该节点插入到合适的位置
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
var sort = function(head, node) {
var current = head;
var pre = null;
while(current) {
if (current.val > node.val) {
if (!pre) {
node.next = head;
head = node;
} else {
pre.next = node;
node.next = current;
}
break;
}
pre = current;
current = current.next;
}
return head;
};
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insertionSortList_1 = function(head) {
if (!head || !head.next) return head;
var current = head;
var pre = null;
while(current) {
if (pre && current.val < pre.val) {
var temp = current.next;
pre.next = temp;
head = sort(head, current);
current = temp;
continue;
}
pre = current;
current = current.next;
}
return head;
};
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var insertionSortList_2 = function(head) {
if (!head || !head.next) return head
let result = new ListNode(null)
result.next = head
let node = head
while (node && node.next) {
if (node.next.val < node.val) {
const rawNext = node.next
node.next = rawNext.next
let cur = result
while (cur && cur.next && cur.next.val < rawNext.val) cur = cur.next
rawNext.next = cur.next
cur.next = rawNext
} else {
node = node.next
}
}
return result.next
}