leetcode InsertionSortList
z
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
import utils.ListNode;

public class InsertionSortList {
/*
Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list


Algorithm of Insertion Sort:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
*/
public static ListNode insertionSortList(ListNode head) {
if (head == null) return null;
ListNode p = head;
ListNode start = new ListNode(0);
start.next = head;

while(p.next != null){
ListNode next = p.next;
if (next.val <= start.next.val){
p.next = next.next;
next.next = start.next;
start.next = next;
}
else if (next.val >= p.val){
p = next.next;

}
else{
p.next = next.next;
ListNode low = start.next;
while(low.val < next.val){
low = low.next;
}
ListNode one = start.next;
while(one.next != low){
one = one.next;
}
next.next = one.next;
one.next = next;
}
}
return start.next;
}
public static void main(String[] args){
ListNode a = new ListNode(0);

}

}