力扣138. 随机链表的复制

Problem: 138. 随机链表的复制

文章目录

题目描述

思路及解法

1.创建Map集合Map<Node, Node> map;创建指针cur指向head;

2.遍历链表将cur作为键,new Node(cur.val)作为值,存入map集合;

3.再次遍历链表,利用map集合存贮的键,将创建的节点(map集合中的值)连接起来,最后返回新链表的头节点

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为链表的大小

空间复杂度:

O ( n ) O(n) O(n)

Code

java 复制代码
/*
// 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 {
    /**
     * Copy List with Random Pointer
     *
     * @param head The head of linked list
     * @return Node
     */
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        Node cur = head;
        Map<Node, Node> map = new HashMap<>();
        while (cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}
相关推荐
Logic1011 小时前
C语言/数据结构二维数组题解:找出行列O个数均为偶数的格子——奇偶性预处理+二次遍历
c语言·数据结构·算法·二维数组·时间复杂度·动态内存分配·奇偶性
程序猿阿森1 小时前
【机器学习实战】朴素贝叶斯算法详解:从概率基础到商品评论情感分析
算法·机器学习·概率论
xxwl5851 小时前
区域赛算法模版第五章---数学与数论
c++·笔记·算法
看浪的路人2 小时前
第6讲:Agent 安全体系——Prompt 注入防御、工具调用审计与输出合规
人工智能·算法
局部有解2 小时前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
垆边人似月.2 小时前
移动长度 k 子串使字符串变成回文
数据结构·算法
pride.li2 小时前
第12章 Python 教程-流程控制:循环结构
linux·服务器·python·算法
海绵宝宝转agent2 小时前
2026-10-16 4算法+1面经
算法
小poop3 小时前
基础排序算法详解——插入、选择与交换排序
算法·排序算法
青蓝智慧马老师3 小时前
想学数据分析但零基础,正确顺序不是先学 Python
大数据·人工智能·算法