-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path147_insertion_sort_list.java
37 lines (29 loc) · 1.1 KB
/
147_insertion_sort_list.java
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
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode sorted = head; // The last sorted node
ListNode insert = head.next; // The node to insert
while(insert != null) {
// if 'insert' >= 'sorted', we simply move forward
if (insert.val >= sorted.val) {
sorted = sorted.next;
insert = sorted.next;
continue;
}
// 'insert' node will be inserted after 'pre'
while(pre != sorted && pre.next.val < insert.val ) {
pre = pre.next;
}
sorted.next = insert.next;
insert.next = pre.next;
pre.next = insert;
// reset 'pre' to dummy node
pre = dummy;
insert = sorted.next;
}
return dummy.next;
}
}