单向链表的插入排序

题目:使用插入排序给单向链表排序。

题目来源:LeetCode--147. Insertion Sort List

原题目:Sort a linked list using insertion sort.

A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
 

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

分析:插入排序想必大家已经都比较熟悉了,为了每次确定插入排序的范围,我们将要插入的结点全部插入到一个新的链表中,这个新链表就是我们要进行插入排序的范围,这样当所有的元素都插入完毕后,直接返回新链表即可,下面看AC代码:

    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode helper = new ListNode(-1);  // 新链表头结点
        ListNode cur = head;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;
            ListNode n = findInsertPosition(helper, cur);  // 在新链表中找到要插入的位置
            linkAfter(n, cur);  // 插入结点
            cur = next;
        }
        return helper.next;
    }

    private ListNode findInsertPosition(ListNode head, ListNode node) {
        while (head.next != null && head.next.val < node.val) {
            head = head.next;
        }
        return head;
    }

    private void linkAfter(ListNode prev, ListNode node) {
        node.next = prev.next;
        prev.next = node;
    }

好了,我们下期见!!!

你可能感兴趣的:(每日刷题系列)