/**
* 147. Insertion Sort List
* 1. Time:O(n2) Space:O(1)
* 2. Time:O(n2) Space:O(1)
*/
// 1. Time:O(n2) Space:O(1)
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode prev = dummy;
ListNode cur = head;
while(cur!=null){
ListNode tmp = cur.next;
while(prev.next!=null && prev.next.val<cur.val) prev = prev.next;
cur.next = prev.next;
prev.next = cur;
prev = dummy;
cur = tmp;
}
return dummy.next;
}
}
// 2. Time:O(n2) Space:O(1)
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(Integer.MIN_VALUE);
ListNode prev = dummy;
ListNode tail = dummy;
ListNode cur = head;
while(cur!=null){
if(tail.val<cur.val){
tail.next = cur;
tail = cur;
cur = cur.next;
}else{
ListNode tmp = cur.next;
while(prev.next!=null && prev.next.val<cur.val) prev = prev.next;
tail.next = tmp;
cur.next = prev.next;
prev.next = cur;
prev = dummy;
cur = tmp;
}
}
return dummy.next;
}
}