Insertion Sort List(链表插入排序)

问题

Sort a linked list using insertion sort.

Have you met this question in a real interview? Yes
Example
Given 1->3->2->0->null, return 0->1->2->3->null.

分析

插入排序

代码

 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    public ListNode insertionSortList(ListNode head) {
        // write your code here
        ListNode res=new ListNode(0);
        res.next=head;
        ListNode temp=res.next;
        ListNode sortedLast=res;
        while(temp!=null){
            head=res.next;
            ListNode last=res;
            while(true){
                if(head==temp){
                    sortedLast=temp;
                    temp=temp.next;
                    break;
                }
                if(head.val<=temp.val){
                    last=head;
                    head=head.next;
                }else{
                    ListNode next=temp.next;
                    last.next=temp;
                    temp.next=head;
                    sortedLast.next=next;
                    temp=next;
                    break;
                }
            }
        }
        return res.next;
    }
}

你可能感兴趣的:(Insertion Sort List(链表插入排序))