插入排序就是,初始时第一个数肯定是有序的,然后看第二个数,如果比第一个数小,那么就将第一个元素后移到第二个位置,然后将原第二个位置的元素插入到第一个位置;接着看第三个数…
以1 3 2为例,初始时1自己肯定有序,然后看第二个元素3,比1大,所以继续看第三个元素2,它比3小,但比1大,因此将3右移到3位置,然后2插入到第二个位置:1 2 3.
public ListNode sortInList(ListNode head) {
// write code here
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode lastNode = head;
ListNode curr = lastNode.next;
while (curr != null) {
if (lastNode.val <= curr.val) lastNode = lastNode.next;
else {
ListNode pre = dummy;
while (pre.next.val <= curr.val) {
pre = pre.next;
}
lastNode.next = curr.next;
curr.next = pre.next; // 1
pre.next = curr;
}
curr = lastNode.next;
}
return dummy.next;
}
对上面注释1的解释:为什么不是 curr.next = lastNode呢?考虑这样一种情况:1 2 3 1.5 4,到3为止已经排好序,即lastNode.val=3,curr.val=1.5,那么pre会停在1的下标处(因为2大于1.5),这时如果curr.next = lastNode,那么就是1.5.next = 3,显然不对;而使用 curr.next = pre.next,那么就是1.5.next = 2,这是正确的。