力扣 中等 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;
    }
}
相关推荐
刀法如飞4 小时前
AI时代:DDD领域驱动建模与Ontology语义建模的区别
java·设计模式·架构
jeffer_liu4 小时前
Spring AI 生产级实战:工具调用
java·人工智能·后端·spring·ai编程
比昨天多敲两行5 小时前
linux 线程概念与控制
java·开发语言·jvm
8Qi85 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
zzhongcy5 小时前
@Transactional 同类内部调用失效 + 两种自代理解决方案
java
AutumnWind04205 小时前
【Intelij IDEA使用手册】
java·ide·intellij-idea
就叫_这个吧7 小时前
Java注解、元注解、自定义注解定义及应用
java·开发语言·注解
Sam_Deep_Thinking7 小时前
聊聊Java中的of
java·开发语言·架构
(●—●)橘子……8 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
NE_STOP8 小时前
Docker--管理监控平台的应用
java