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));
    }
}

结果:

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-01-25 14:16:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-25 14:16:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-25 14:16:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-25 14:16:02       18 阅读

热门阅读

  1. 编程笔记 html5&css&js 051 CSS表格2-2

    2024-01-25 14:16:02       28 阅读
  2. nestjs之适配器模式的应用

    2024-01-25 14:16:02       34 阅读
  3. 编程笔记 html5&css&js 054 CSS默认值

    2024-01-25 14:16:02       30 阅读
  4. HJ8 合并表记录【C语言】

    2024-01-25 14:16:02       34 阅读
  5. jmeter常问问题

    2024-01-25 14:16:02       33 阅读
  6. Vue2 和Vue3 有什么区别

    2024-01-25 14:16:02       29 阅读
  7. ros中调用opencv绘图测试

    2024-01-25 14:16:02       33 阅读
  8. CaptureRequest部分参数说明

    2024-01-25 14:16:02       38 阅读
  9. 要在 Ubuntu 上开启 SSH(Secure Shell)服务器

    2024-01-25 14:16:02       31 阅读