使用插入排序對鏈表進行排序(Sort a linked list using insertion sort.):
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return head;
}
ListNode toInsert = head;
ListNode newHead = null;
while (toInsert != null) {
ListNode cur = newHead;
ListNode next = toInsert.next;
// 判斷頭部
if (cur == null||toInsert.val <= newHead.val) {
toInsert.next = cur;
newHead = toInsert;
} else {
while (cur.next != null) {
if (cur.val <= toInsert.val && toInsert.val <= cur.next.val) {
toInsert.next = cur.next;
cur.next = toInsert;
break;
}
cur =cur.next;
}
//如果待插入的數是最大的,就把它放在後面
if (cur.next == null) {
cur.next = toInsert;
toInsert.next = null;
}
}
toInsert = next;
}
return newHead;
}