对链表进行排序 (插入和归并法)

插入排序来排序链表(时间复杂度O(n2))

/**
 * 对链表进行插入排序 O(n^2)。 输入: 4->2->1->3 ,输出: 1->2->3->4
 * 思路: pre  pre.next        head   (head.next)cur
 *        2      9       10    15           8
 */
public class LC147 {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre;
        while (head != null && head.next != null) {
            if (head.val < head.next.val) {
                head = head.next;
                continue;
            }
            pre = dummy;
            ListNode cur = head.next;
            while (pre.next.val < cur.val) {
                pre = pre.next;
            }
            head.next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
        }
        return dummy.next;
    }
}

  

归并排序来排序链表(时间复杂度O(nlogn))

/**
 * 思路:归并排序 O(n log n)    O(1)
 * 找出链表中间位置:设置一个慢指针slow,一个快指针fast
 * 画图可知,fast != null 、fast.next != null 、fast.next.next == null 时
 * 还需要往后走一次,所以终止条件为 fast != null && fast.next != null
 */
public class LC148 {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
        ListNode h = new ListNode(0);
        ListNode res = h;
        while (left != null && right != null) {
            if (left.val < right.val) {
                h.next = left;
                left = left.next;
            } else {
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        h.next = left != null ? left : right;
        return res.next;
    }
}

通过比较147的插入排序(n2)和148的归并排序(nlogn),最好使用归并排序

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值