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

相关推荐
七夜zippoe17 小时前
事务方案选型全景图:金融与电商场景的实战差异与落地指南
java·分布式·事务
爱编程的化学家18 小时前
代码随想录算法训练营第六天 - 哈希表2 || 454.四数相加II / 383.赎金信 / 15.三数之和 / 18.四数之和
数据结构·c++·算法·leetcode·双指针·哈希
杨二K18 小时前
认识HertzBeat的第一天
java·hertzbeat
DevilSeagull18 小时前
JavaScript WebAPI 指南
java·开发语言·javascript·html·ecmascript·html5
期待のcode20 小时前
Spring框架1—Spring的IOC核心技术1
java·后端·spring·架构
葵野寺20 小时前
【RelayMQ】基于 Java 实现轻量级消息队列(七)
java·开发语言·网络·rabbitmq·java-rabbitmq
书院门前细致的苹果21 小时前
JVM 全面详解:深入理解 Java 的核心运行机制
java·jvm
上官浩仁21 小时前
springboot excel 表格入门与实战
java·spring boot·excel
木心爱编程21 小时前
C++链表实战:STL与手动实现详解
开发语言·c++·链表
Hello.Reader1 天前
从零到一上手 Protocol Buffers用 C# 打造可演进的通讯录
java·linux·c#