leetcode:排序链表(递归)

题目:

给定链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

示例 1:

输入:head = [4,2,1,3]
输出:[1,2,3,4]

示例 2:

输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]

示例 3:

输入:head = []
输出:[]

提示:

链表中节点的数目在范围 [0, 5 * 104] 内

-105 <= Node.val <= 105

代码+思路(注释):

class Solution {
public ListNode sortList(ListNode head) {
        //直接调用最后结果:head是头,tail==null;也就是结尾null
        return sort(head,null);
    }

    public ListNode mergeTwoLists(ListNode list1,ListNode list2) {
        //归并排序的思想
        //在下一个函数中我们要掉用他
        //这个是合并排序两个升序链表
        //后面我们要切割链表,使他成为2个升序链表
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode dammyHead = new ListNode(Integer.MAX_VALUE);//虚拟头结点
        ListNode pre = dammyHead;//动的结点//也是新链表的指针
        ListNode cur1 = list1;//两个指针
        ListNode cur2 = list2;
        //开始向新链表插入
        while (cur1 != null && cur2 != null) {
            if (cur1.val > cur2.val) {
                pre.next = cur2;
                cur2 = cur2.next;
            } else {
                pre.next = cur1;
                cur1 = cur1.next;
            }
            pre = pre.next;
        }
        if (cur1 == null) {
            pre.next = cur2;
        }//因为是排好序的2个链表
        else {
            pre.next = cur1;
        }
        return dammyHead.next;//返回虚拟头结点后面部分
    }

    public ListNode sort(ListNode head,ListNode tail){
        //因为链表本身没有排序
        if(head==null){
            return head;
        }
        if(head.next==tail){
            head.next=null;
            return head;
        }
        ListNode node1=head;//两个指针
        //一个快,一个慢
        ListNode node2=head;
        //找中间结点
        while(node2!=tail){
            node1=node1.next;
            node2=node2.next;
            if(node2!=tail){
                node2=node2.next;
            }
        }
        //多次调用sort,每次把各部分再分割
        //在调用合并(归并)函数//每次排一部分
        return mergeTwoLists(sort(head,node1),sort(node1,tail));
    }
}

结果:

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值