LeetCode 143.重排链表

题目

给定一个单链表 L的头节点 head ,单链表 L 表示为:

复制代码
L0 → L1 → … → Ln - 1 → Ln

请将其重新排列后变为:

复制代码
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路:找中点,反转,前后逐一重排

代码

java 复制代码
class Solution {
    public void reorderList(ListNode head) {
        ListNode mid = middleNode(head);
        ListNode head2 = reverseList(mid);
        while (head2.next != null) {
            ListNode nxt = head.next;
            ListNode nxt2 = head2.next;
            head.next = head2;
            head2.next = nxt;
            head = nxt;
            head2 = nxt2;
        }
    }
    private ListNode middleNode(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    private ListNode reverseList(ListNode head) {
        ListNode pre = null, cur = head;
        while (cur != null) {
            ListNode nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}

性能

时间复杂度o(n)

空间复杂度o(1)

相关推荐
_清歌14 小时前
DSpark 深度解读:DeepSeek-V4 如何用「半自回归」把推理速度提升 85%
算法
统计实现局14 小时前
SVD 的三步走:双对角化、Givens 收敛、排序
算法
躬行见万象14 小时前
《VLA 系列》UniLab 强化训练 | G1 机器人 |复现
算法
统计实现局14 小时前
对称不定分解(Bunch-Kaufman):为什么 Cholesky 不够用
算法
统计实现局14 小时前
dqrsl 拆解:拿着 QR 结果能算出哪 5 种东西
算法
统计实现局14 小时前
为什么 Cholesky 求逆比 Gauss-Jordan 快一倍——行列式溢出防护详
算法
To_OC1 天前
LC 994 腐烂的橘子:人人都说是 BFS 入门题,我却写了三遍才过
javascript·算法·leetcode
金銀銅鐵1 天前
[Python] 扩展欧几里得算法
python·数学·算法
To_OC1 天前
LC 200 岛屿数量:经典 DFS 入门题,我第一次写居然连方向都搞错了
javascript·算法·leetcode