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

相关推荐
微风粼粼7 分钟前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
缘来是庄11 分钟前
设计模式之中介者模式
java·设计模式·中介者模式
rebel41 分钟前
若依框架整合 CXF 实现 WebService 改造流程(后端)
java·后端
代码的余温2 小时前
5种高效解决Maven依赖冲突的方法
java·maven
慕y2742 小时前
Java学习第十六部分——JUnit框架
java·开发语言·学习
paishishaba2 小时前
Maven
java·maven
张人玉2 小时前
C# 常量与变量
java·算法·c#
Java技术小馆3 小时前
GitDiagram如何让你的GitHub项目可视化
java·后端·面试
学不动CV了3 小时前
数据结构---链表结构体、指针深入理解(三)
c语言·arm开发·数据结构·stm32·单片机·链表
Codebee3 小时前
“自举开发“范式:OneCode如何用低代码重构自身工具链
java·人工智能·架构