Insertion Sort List

Sort a linked list using insertion sort.

Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy=new ListNode(0), cur=head;
        while(cur!=null){
            ListNode pre = dummy;
            while(pre.next!=null && pre.next.val<cur.val) pre=pre.next;
            ListNode tmp = pre.next;
            pre.next = cur;
            cur = cur.next;
            pre.next.next = tmp;
        }
        return dummy.next;
    }
}
comments powered by Disqus