排序链表

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4

示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode slow = head, fast = head, pre = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        pre.next = null;
        return merge(sortList(head), sortList(slow));
    }
    public ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (l1 != null) cur.next = l1;
        if (l2 != null) cur.next = l2;
        return dummy.next;
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
排序链表问题是指对一个链表进行排序。其中,可以使用链表自顶向下归并排序的方法进行排序。具体过程如下: 1. 找到链表的中点,以中点为分界,将链表拆分成两个子链表。可以通过快慢指针的方式来找到链表的中点。快指针每次移动2步,慢指针每次移动1步,当快指针到达链表末尾时,慢指针指向的节点即为链表的中点。 2. 对两个子链表分别进行排序。可以使用递归的方式对子链表进行排序,直到链表为空或者只包含1个节点时,不需要再进行拆分和排序。 3. 将两个排序后的子链表合并,得到完整的排序后的链表。可以使用合并两个有序链表的方法来实现,依次比较两个链表头节点的值,将较小的节点加入到新的链表中。 4. 返回排序后的链表。 以下是Java代码示例: ```java class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode slow = head, 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 dummy = new ListNode(0); ListNode curr = dummy; while (left != null && right != null) { if (left.val < right.val) { curr.next = left; left = left.next; } else { curr.next = right; right = right.next; } curr = curr.next; } curr.next = left != null ? left : right; return dummy.next; } } ``` 以上是一种解决Java排序链表问题的方法,通过链表自顶向下归并排序的思想,可以对链表进行排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值