力扣--LCR 154.复杂链表的复制

题目

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

提示:

复制代码
-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。

代码

/*

// Definition for a Node.

class Node {

int val;

Node next;

Node random;

复制代码
public Node(int val) {
    this.val = val;
    this.next = null;
    this.random = null;
}

}

*/

class Solution {

public Node copyRandomList(Node head) {

if(head == null){

return null;

}

// 复制链表节点

Node cur = head;

while(cur != null){

Node next = cur.next;

cur.next = new Node(cur.val);

cur.next.next = next;

cur = next;

}

复制代码
    // 复制随机节点
    cur = head;
    while(cur != null){
        Node curNew = cur.next;
        curNew.random = cur.random == null ? null : cur.random.next;
        cur = cur.next.next;
    }

    // 拆分,比如把 A->A1->B->B1->C->C1拆分成 A->B->C和A1->B1->C1
    Node headNew = head.next;
    cur = head;
    Node curNew = head.next;
    while(cur != null){
        cur.next = cur.next.next;
        cur = cur.next;
        curNew.next = cur == null ? null : cur.next;
        curNew = curNew.next;
    }

    return headNew;
}

}

时间复杂度:O(n)

额外空间复杂度:O(1)

相关推荐
午彦琳22 分钟前
2026.9.17
数据结构·算法·leetcode
西峰u24 分钟前
Java单例模式|从基础到多线程安全
java·java单例模式
ClinicTech25 分钟前
实验室洗瓶机的清洗系统架构与自动化控制解析
java·python
linmengmeng_131439 分钟前
【总结】MyBatis-Plus批量插入与清表的正确姿势
java·spring boot·mysql·mybatis
木井巳44 分钟前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
Sam_Deep_Thinking1 小时前
new Thread()之后发生了什么?
java·后端·面试·程序员
泡海椒1 小时前
规则引擎对比:JQuick-Java vs Drools 轻量场景选型对比
java·开发语言
wno7041 小时前
Spring Security短信验证码登录
java·python·spring
步行cgn1 小时前
Spring util 命名空间详解
java·后端·spring
古法安卓2 小时前
Android-休眠唤醒后onLocationChanged没有数据问题排查
android·java·android studio