leetcod第148题 排序列表(归并排序)×

class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
       
        //统计链表长度
        int length = 0;
        while(head != null){
            length++;
            head = head.next;
        }
        head = dummy.next;
        //共循环logn次,每次循环都将进行一次全链表的遍历并逐步恢复次序
        for(int i = 1;i < length; i += i){
            //将链表分为四段,第一段为已排序的部分,第二段为待排序的第一部分(由first表示头节点),第三段为待排序的第二部分(由second表示头节点),第四段为未排序的部分(由head节点表示头节点)
            ListNode succ = dummy;
            ListNode first = null;
            ListNode second = null;
            while(head != null){
                first = head;
                head = cutFromHead(head,i);
                second = head;
                head = cutFromHead(head,i);
                //将两段链接到succ尾部,并移动succ
                succ.next = mergeLists(first,second);
                while(succ.next != null) succ = succ.next;
            }
            head = dummy.next;
        }
        return dummy.next;
        
    }
    
    //将链表从head节点开始的n个节点切断,并返回第n+1个节点
    public ListNode cutFromHead(ListNode head,int n){
        while(head != null && --n > 0){
            head = head.next;
        }
        if(head == null) return null;
        ListNode next = head.next;
        head.next = null;
        return next;
    }     
    
    //将两个链表合并
    public ListNode mergeLists(ListNode first,ListNode second){
        if(first == null) return second;
        if(second == null) return first;
        ListNode dummy = new ListNode(-1);
        ListNode succ = dummy;
        while(first != null && second != null){
            if(first.val < second.val){
                succ.next = first;
                first = first.next;
            }else{
                succ.next = second;
                second = second.next;
            }
            succ = succ.next;
        }
        succ.next = first != null? first : second;
        return dummy.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值