147. 对链表进行插入排序

递归

class Solution {
    public ListNode insertionSortList(ListNode head) {

        /**
         * 终止条件
         */
        if (head == null || head.next == null){
            return head;
        }

        ListNode next = insertionSortList(head.next);

        /**
         * 如果头节点是最小的,直接连接上
         */
        if (head.val <= next.val){

            head.next = next;
            return head;
        }

        /**
         * 否则遍历链表找到head的位置再插入
         */
        ListNode cur = next;

        while (cur.next != null && head.val > cur.next.val){
            cur = cur.next;
        }

        ListNode temp = cur.next;
        cur.next = head;
        head.next = temp;

        return next;
    }
}

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/insertion-sort-list/

posted @ 2021-12-17 10:21  振袖秋枫问红叶  阅读(32)  评论(0)    收藏  举报