力扣 中等 143.重排链表

文章目录

题目介绍


题解

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

    // 876. 链表的中间结点
    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;
    }

    // 206. 反转链表
    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;
    }
}
相关推荐
RainbowSea1 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea1 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑5 小时前
Jpa使用union all
java·spring boot·后端
用户3721574261355 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊6 小时前
Java学习第22天 - 云原生与容器化
java
渣哥8 小时前
原来 Java 里线程安全集合有这么多种
java
间彧8 小时前
Spring Boot集成Spring Security完整指南
java
间彧9 小时前
Spring Secutiy基本原理及工作流程
java
Java水解10 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆12 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试