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

相关推荐
间彧1 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧1 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧1 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng1 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663672 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧2 小时前
ThreadLocal实现原理与应用实践
java
若水不如远方2 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty
用户7493636848432 小时前
【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果
java
SimonKing3 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员