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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head == null) return null;
        ListNode curNode = null;
        ListNode preNode=null;
        ListNode nextNode=null;
        ListNode node = null;
        curNode = head.next;
        head.next = null;
        while(curNode!=null)//当前要插入的节点
        {
            node = curNode.next;//保存下一个节点
            if(curNode.val < head.val)//比头结点还小,则成为新的头结点
            {
                curNode.next = head;
                head = curNode;
            }
            else
            {
                preNode = head;
                nextNode = head.next;
                while(nextNode!=null && nextNode.val<curNode.val)//找到合适位置
                {
                    preNode = nextNode;
                    nextNode = nextNode.next;
                }
                curNode.next = preNode.next;
                preNode.next = curNode;
            }
            curNode = node;
        }
        return head;//返回新的头结点
    }
}
原文地址:https://www.cnblogs.com/23lalala/p/3506825.html