147. Insertion Sort List

Sort a linked list using insertion sort.

 

public ListNode InsertionSortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode stand = new ListNode(0);
        ListNode p = head;
        ListNode s = stand;
        ListNode nextNode = null;
        while(p != null)
        {
            nextNode = p.next;
            while(s.next != null && s.next.val <= p.val)
            {
                s = s.next;
            }
            p.next = s.next;
            s.next = p;
           
            s= stand;
            p = nextNode;
        }
        
        return stand.next;
    }

 

 
posted @ 2016-09-13 12:57  咖啡中不塌缩的方糖  阅读(109)  评论(0编辑  收藏  举报