Leetcode - Insertion Sort List

Sort a linked list using insertion sort.

[分析]
数组的插入排序通常做法是从当前元素往前遍历找到插入点,而单向链表无法回溯,于是每次从头开始寻找插入点。使用dummy额外节点技巧可使实现更简洁。
开始未将已排序部分和未排序部分分开,会死循环从而OutOfMemory,简单带入2->1 可看出bug。

public class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        ListNode prev = dummy;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            prev = dummy;
            while (prev.next != null && prev.next.val <= curr.val)
                prev = prev.next;
            curr.next = prev.next;
            prev.next = curr;
            curr = next;
        }
        return dummy.next;
    }
    // Out of memory version
    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode curr = head.next;
        while (curr != null) {
            ListNode next = curr.next;
            prev = dummy;
            while (prev.next != null && prev.next.val <= curr.val)
                prev = prev.next;
            curr.next = prev.next;
            prev.next = curr;
            curr = next;
        }
        return dummy.next;
    }
}

你可能感兴趣的:(Leetcode - Insertion Sort List)