链表排序之插入排序算法:
public static ListNode insertionSortList(ListNode head) {
if (null == head || null == head.next){
return head;
}
ListNode preHead = new ListNode(-1);
preHead.next = head;
ListNode cur = head;
while (null != cur){
ListNode pre = preHead;
ListNode next = cur.next;
while (null != next && cur.val <= next.val){
next = next.next;
cur = cur.next;
}
if (null == next){
break;
}
while (pre.next.val <= next.val){
pre = pre.next;
}
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return preHead.next;
}
排序前:6 2 8 4 9 5 1 3 7
排序后:1 2 3 4 5 6 7 8 9