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

相关推荐
vvilkim1 分钟前
Python multiprocessing 模块全面解析:解锁真正的并行计算能力
java·开发语言
专注写bug16 分钟前
Java——pdf增加水印
java·pdf
橘子青衫22 分钟前
Java线程调度机制剖析:机制、状态与优先级管理
java·后端
Cloud_.37 分钟前
蓝桥杯-小明的背包(动态规划-Java)
java·蓝桥杯·动态规划·01背包·蓝桥杯算法实战分享
Better Rose1 小时前
【2024年蓝桥杯Java B组】省赛真题详细解析
java·蓝桥杯
2401_897930061 小时前
微信小程序中的openid的作用
java
毕小宝2 小时前
Java 解析日期格式各个字段含义温习
java
pwzs2 小时前
Spring 框架的核心基础:IoC 和 AOP
java·后端·spring
小美爱刷题2 小时前
力扣DAY40-45 | 热100 | 二叉树:直径、层次遍历、有序数组->二叉搜索树、验证二叉搜索树、二叉搜索树中第K小的元素、右视图
数据结构·算法·leetcode
xrkhy2 小时前
java基础语法(3)数组
java·开发语言