首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >链表系列一>重排链表

链表系列一>重排链表

作者头像
用户11305962
发布2025-04-28 11:09:04
发布2025-04-28 11:09:04
960
举报
文章被收录于专栏:学习学习

题目:

链接: link

这里是引用
这里是引用

解析:

在这里插入图片描述
在这里插入图片描述

细节:

在这里插入图片描述
在这里插入图片描述

代码:

代码语言:javascript
复制
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public void reorderList(ListNode head) {
        //边界
        if (head == null || head.next == null || head.next.next == null) return;

        ListNode fast = head,slow = head;

        //1.找链表的中间节点
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        
        //2.把 slow 后面的部分链表给逆序 - 头插法
        ListNode prev = new ListNode(0);
        ListNode cur = slow.next;
        slow.next = null;//把两个链表断开

        while(cur != null){
            //记录cur后的节点,不然后面就断开了
            ListNode next = cur.next;
            cur.next = prev.next;
            prev.next = cur;
            cur = next;
        }

        //3.合并两个链表(第一个头--》head, 第二个的头--》prev)
        ListNode tmp = new ListNode(0);
        ListNode cur1 = head,cur2 = prev.next;
        ListNode curN = tmp;

        while(cur1 != null){
            curN.next = cur1;
            curN = cur1;
            cur1 = cur1.next;

            if(cur2 != null){
                curN.next = cur2;
                curN = cur2;
                cur2 = cur2.next;
            }
        
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-04-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:
  • 解析:
  • 细节:
  • 代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档