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

相关推荐
nju_spy5 分钟前
力扣每日一题(11.10-11.29)0-1 和 k 整除系列
python·算法·leetcode·前缀和·单调栈·最大公约数·0-1背包
无风之翼12 分钟前
android12下拉菜单栏界面上方显示无内容
android·java
程序员梁白开12 分钟前
从源码到实战:线程池处理任务的完整流程解析
java·jvm·spring·java-ee
u***13716 分钟前
Tomcat的升级
java·tomcat
t***p93518 分钟前
springboot项目读取 resources 目录下的文件的9种方式
java·spring boot·后端
C***115031 分钟前
Tomcat下载,安装,配置终极版(2024)
java·tomcat
ScriptBIN37 分钟前
Maven高级
java·maven
Empty_77740 分钟前
K8S-Pod资源对象
java·容器·kubernetes
D***y20142 分钟前
SpringSecurity 实现token 认证
java
N***77881 小时前
Tomcat 乱码问题彻底解决
java·tomcat