力扣 中等 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;
    }
}
相关推荐
Ramos丶3 分钟前
【ABAP】 从无到有 新建一个Webdynpro程序
java·前端·javascript
sniper_fandc14 分钟前
SpringMVC详解
java·springmvc
TT哇1 小时前
【Java EE初阶】计算机是如何⼯作的
java·redis·java-ee
Fireworkitte8 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
weixin-a153003083168 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
DCTANT8 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.9 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
Alfred king9 小时前
面试150 生命游戏
leetcode·游戏·面试·数组
黄雪超9 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice9 小时前
对象的finalization机制Test
java·开发语言·jvm