您的位置:首页 > 其它

LeetCode 147 Insertion Sort List

2015-12-02 09:15 495 查看

题目描述

Sort a linked list using insertion sort.

代码

[code]    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;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: