LeetCode 147 Insertion Sort List

题目描述

Sort a linked list using insertion sort.

代码

    public ListNode insertionSortList(ListNode head) {

        if (head == null)
            return null;
        if (head.next == null)
            return head;

        final ListNode _head = new ListNode(Integer.MIN_VALUE);
        _head.next = head;

        head = head.next;
        _head.next.next = null;

        next: while (head != null) {

            ListNode taken = head;
            head = head.next;

            ListNode cur = _head.next;
            ListNode last = _head;

            while (cur != null) {

                if (cur.val > taken.val) {
                    // insert
                    last.next = taken;
                    taken.next = cur;

                    continue next;

                }

                cur = cur.next;
                last = last.next;
            }

            last.next = taken;
            taken.next = null;

        }

        return _head.next;

    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/yano_nankai/article/details/50143637
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞