LeetCode 147 Insertion Sort List

来源:互联网 发布:算法导论 python 编辑:程序博客网 时间:2024/04/28 22:17

题目描述

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;    }
1 0
原创粉丝点击