力扣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);
    }
}
相关推荐
练习时长一年3 分钟前
LeetCode热题100(分割等和子集)
算法·leetcode·职场和发展
52Hz1188 分钟前
力扣148.排序链表
leetcode
七号驿栈14 分钟前
07_汽车信息安全算法在线验证工具(测试报告)
算法
啦哈拉哈31 分钟前
【Python】知识点零碎学习4
python·学习·算法
iAkuya35 分钟前
(leetcode)力扣100 46二叉树展开为链表(递归||迭代||右子树的前置节点)
windows·leetcode·链表
爱喝可乐的老王36 分钟前
线性回归模型案例:广告投放效果预测
算法·回归·线性回归
程序员-King.1 小时前
day151—双端队列—找树左下角的值(LeetCode-513)
算法·leetcode·二叉树·双端队列·队列
苦藤新鸡1 小时前
15 .数组右移动k个单位
算法·leetcode·动态规划·力扣
狐572 小时前
2026-01-19-牛客每日一题-阅读理解
笔记·算法·牛客
氷泠2 小时前
路径总和系列(LeetCode 112 & 113 & 437 & 666)
leetcode·前缀和·深度优先·路径总和