剑指offer 专项突破版 77、链表排序

题目链接

思路
  • 这个题目可以用归并排序来做~
  • 首先需要一个split函数,用于分隔链表(相当于数组归并排序的取mid)
  • 然后需要一个merge函数,用于把两个链表归并,并返回归并后的头指针~
  • 最后递归调用即可~ 注意递归的条件
class Solution {

    private ListNode split(ListNode head) {

        ListNode slow = head, fast = head.next.next;
        while (null != fast) {
            slow = slow.next;
            fast = fast.next;

            if (null != fast)
                fast = fast.next;
        }
        fast = slow.next;
        slow.next = null;

        return fast;
    }

    private ListNode merge(ListNode first, ListNode second) {
        ListNode dummy = new ListNode(0), head = dummy;

        while (null != first && null != second) {
            if (first.val < second.val) {
                head.next = first;
                first = first.next;
            } else {
                head.next = second;
                second = second.next;
            }
            head.next.next = null;
            head = head.next;
        }
        head.next = null == first ? second : first;

        return dummy.next;
    }

    public ListNode sortList(ListNode head) {
        if (null == head || null == head.next)
            return head;

        ListNode mid = split(head);        
        ListNode left = sortList(head), right = sortList(mid);
        
        return merge(left,right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值