力扣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);
    }
}
相关推荐
mit6.8242 小时前
前后缀分解
算法
独自破碎E2 小时前
判断链表是否为回文
数据结构·链表
你好,我叫C小白2 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林5 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway5 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No76 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区6 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫6 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****6 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者7 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶