LeetCode-147. 对链表进行插入排序

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/love905661433/article/details/84842607

题目

对链表进行插入排序。

在这里插入图片描述
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

插入排序算法:

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

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

解题

  • 插入排序写法如下
  • 这题使用归并排序写也能过, 而且性能更高, 不过题目要求使用插入排序, 这里就使用插入排序来做了
class Solution {
    public ListNode insertionSortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        // head~pre是排好序的部分
        ListNode pre = head;
        // 第一个元素默认是有序的
        ListNode cur = head.next;
        while (cur != null) {
            // 寻找插入位置
            ListNode insertPre = findInsertIndexPre(dummyHead, cur);
            // 这种情况表示当前节点不需要换位置
            if (insertPre == pre) {
                pre = cur;
                cur = cur.next;
            } else {
                // cur的需要插入到insertPre后面的位置
                pre.next = cur.next;
                cur.next = insertPre.next;
                insertPre.next = cur;

                // 移动cur
                cur = pre.next;
            }
        }

        return dummyHead.next;
    }

    /**
     * 查找cur要插入位置的前一个节点
     * @param head
     * @param cur
     * @return
     */
    private ListNode findInsertIndexPre(ListNode head, ListNode cur ){
        while (head.next != cur) {
            if (head.next.val >= cur.val) {
                return head;
            }
            head = head.next;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/love905661433/article/details/84842607
今日推荐