天天看点

insertion-sort-listinsertion-sort-list

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){
            return null;
        }
        ListNode newHead=new ListNode(head.val),pre=head;
        for(ListNode q=head.next;q!=null;q=q.next){
            for(ListNode p=newHead;p!=null;pre=p,p=p.next){
                if(q.val<=p.val){
                    ListNode newNode=new ListNode(q.val);
                    if(p==newHead){
                        newNode.next=newHead;
                        newHead=newNode;
                    }else{
                        newNode.next=p;
                        pre.next=newNode;
                    }
                    break;
                }else{
                    if(p.next==null){
                        p.next=new ListNode(q.val);
                        break;
                    }
                }
            }

        }
        return newHead;
    }
}