Sunday, January 11, 2015

LeetCode 147: Insertion Sort List

Sort a linked list using insertion sort.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if(head==null || head.next==null)
            return head;
        
        // Create a new node helper and put it before head
        // In case the position of head is also changed
        ListNode helper = new ListNode(0);
        helper.next = head;

        ListNode pre; // Find the the insertion position of smallNode (After operation, pre -> smallMode)
        ListNode cur = head; // Current node
        ListNode smallNode; // After current node but smaller than it
        
        while (cur!=null && cur.next!=null)  
        {  
            if (cur.val <= cur.next.val)
                cur = cur.next;
            else
            {
                smallNode = cur.next;
                
                pre = helper;
                
                while (pre.next!=null && pre.next.val<smallNode.val)
                    pre = pre.next;
                
                // Insert smallNode after pre Node    
                ListNode tmp = pre.next;
                pre.next = cur.next;
                cur.next = smallNode.next;
                smallNode.next = tmp;
            }
        }
        
        // Skip the new empty head
        return helper.next;
    }
}

No comments:

Post a Comment