Friday, April 10, 2015

147. Insertion Sort List Leetcode Java

Sort a linked list using insertion sort.
Solution:
Just like insertion sort in the array. 
1.Find the insertion position,
2. Insert into the right postion
Have to check if the current node is already in the right position. If yes, do nothing. 
 public ListNode insertionSortList(ListNode head) {  
    if(head==null || head.next==null) return head;  
    ListNode preDummy=new ListNode(0);  
    preDummy.next=head;  
    ListNode tail=head;  
    while(tail.next!=null){  
      ListNode cur=tail.next;  
      ListNode pre=preDummy;  
      while(cur.val>pre.next.val) pre=pre.next;  
      if(pre!=tail){  
        tail.next=cur.next;  
        cur.next=pre.next;  
        pre.next=cur;  
      }  
      else tail=tail.next;  
    }  
    return preDummy.next;  
   }  

No comments:

Post a Comment