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) {
        ListNode h = new ListNode(Integer.MIN_VALUE);//新建一个头结点
        while(head!=null) {
            ListNode tmp = head.next;
            ListNode p = h;
            while(p!=null) {
                if(p.next==null) {
                    p.next = head;
                    head.next = null;
                    break;
                }
                else if(head.val>=p.val&&head.val<p.next.val) {
                    head.next = p.next;
                    p.next = head;
                    break;
                }
                p = p.next;
            }
            head = tmp;
        }
        return h.next;
    }
}

 

posted @ 2015-03-24 15:50  mrpod2g  阅读(77)  评论(0编辑  收藏  举报