其他分享
首页 > 其他分享> > 147. 对链表进行插入排序

147. 对链表进行插入排序

作者:互联网

对链表进行插入排序。

插入排序算法:

插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
重复直到所有输入数据插入完为止。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/insertion-sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null) {
            return head;
        }

        ListNode helper = new ListNode(0);
        helper.next = head;
        ListNode tail = head;
        ListNode cur = head.next;

        while (cur != null) {
            if (cur.val >= tail.val) {
                tail = cur;
            } else {
                ListNode prev = helper;
                while (prev.next.val <= cur.val) {
                    prev = prev.next;
                }
                tail.next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
            }
            cur = tail.next;
        }

        return helper.next;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

标签:147,head,ListNode,cur,helper,插入排序,链表,tail
来源: https://www.cnblogs.com/tianyiya/p/15785389.html