Problem: Sort a linked list using insertion sort.
Insersion Sort:
Loop to find min/max number, then move to specific position,
after n loops to get sorted result
Idea: Use dummy node, tempDummy;
public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head==null || head.next==null) return head;
ListNode dummy=new ListNode(0);
ListNode cur=head;
while(cur!=null){
//save cur.next and use later
ListNode curNext=cur.next;
ListNode tempDummy=dummy;
while (tempDummy.next!=null && tempDummy.next.val<cur.val){
tempDummy=tempDummy.next;
}
cur.next=tempDummy.next;
tempDummy.next=cur;
cur=curNext;
}
return dummy.next;
}
}