力扣--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)

相关推荐
alonewolf_9923 分钟前
深入Spring核心原理:从Bean生命周期到AOP动态代理全解析
java·后端·spring
天远Date Lab24 分钟前
Python实现用户消费潜力评估:天远个人消费能力等级API对接全攻略
java·大数据·网络·python
没有bug.的程序员8 小时前
服务安全:内部服务如何防止“裸奔”?
java·网络安全·云原生安全·服务安全·零信任架构·微服务安全·内部鉴权
一线大码8 小时前
SpringBoot 3 和 4 的版本新特性和升级要点
java·spring boot·后端
weixin_440730508 小时前
java数组整理笔记
java·开发语言·笔记
weixin_425023008 小时前
Spring Boot 实用核心技巧汇总:日期格式化、线程管控、MCP服务、AOP进阶等
java·spring boot·后端
一线大码8 小时前
Java 8-25 各个版本新特性总结
java·后端
2501_906150569 小时前
私有部署问卷系统操作实战记录-DWSurvey
java·运维·服务器·spring·开源
better_liang9 小时前
每日Java面试场景题知识点之-TCP/IP协议栈与Socket编程
java·tcp/ip·计算机网络·网络编程·socket·面试题
niucloud-admin9 小时前
java服务端——controller控制器
java·开发语言