链表相关面试题
2017-10-03 13:29
288 查看
使用插入排序对链表进行排序(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; }