leetcode--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 result = null;
        if(head != null){
            ListNode newHead = new ListNode(0);
            newHead.next = head;
            ListNode sortedTail = head;
            while(sortedTail.next != null){
                ListNode secondNode = sortedTail.next;
                ListNode searchNode = newHead;
                while(searchNode != secondNode){
                    if(searchNode.next.val > secondNode.val)
                        break;
                    else
                        searchNode = searchNode.next;
                }
                if(searchNode != secondNode){
                    sortedTail.next = secondNode.next;
                    secondNode.next = searchNode.next;
                    searchNode.next = secondNode;                    
                }
                else
                    sortedTail = secondNode;                
            }
        result = newHead.next;   
        }
        return result;
    }
}

  

原文地址:https://www.cnblogs.com/averillzheng/p/3552649.html