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

相关推荐
A boy CDEF girl15 分钟前
【JavaEE】线程池
java·java-ee
Joeysoda15 分钟前
JavaEE进阶(2) Spring Web MVC: Session 和 Cookie
java·前端·网络·spring·java-ee
Y雨何时停T38 分钟前
深入理解 Java 虚拟机之垃圾收集
java·开发语言
动亦定1 小时前
物联网设备接入系统后如何查看硬件实时数据?
java·物联网
誓约酱1 小时前
(每日一题) 力扣 283 移动零
linux·c语言·数据结构·c++·算法·leetcode
码农CV1 小时前
Java基础面试题全集
java·面试
B站计算机毕业设计超人1 小时前
计算机毕业设计SpringBoot+Vue.js民族婚纱预定系统(源码+文档+PPT+讲解)
java·vue.js·spring boot·后端·毕业设计·课程设计·毕设
镜花水月linyi2 小时前
记一次SpringBoot传给前端Long类型精度丢失
java·后端
技术咖啡馆C2 小时前
二、IDE集成AI助手豆包MarsCode保姆级教学(使用篇)
java·ide·ai编程·idea-plugin·marscode
时雨h2 小时前
芋道源码 —— Spring Boot 缓存 Cache 入门
java·后端·spring