LeetCode 138. Copy List with Random Pointer 复制带随机指针的链表(Java)

题目:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index]where:

  • val: an integer representing Node.val
  • random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
    在这里插入图片描述
    Constraints:
  • -10000 <= Node.val <= 10000
  • Node.random is null or pointing to a node in the linked list.
  • Number of Nodes will not exceed 1000.

解答:

注意题目中要求的是深拷贝,即新链表的每个节点必须是新new出来的,否则就只是之前旧链表的引用,而非深拷贝。

基本思路为:

  1. 复制给定链表中的每一个节点,将其插入到给定链表中原节点的后面。
  2. 复制random节点。由于新节点就在原节点的后面,因此,依次检测给定链表中的每个节点,若random不为空,则将它的下一个节点(对应新节点)的random指针指向原节点random指针所指节点的下一个节点。
  3. 最后再将该链表拆分成新、旧两个链表,返回新链表。
    一个详细的解答如下所示:复制带有随机指针的链表

这里我们采用一种更为简便的解法

  1. 将原链表先全部遍历一遍,创建新节点,并在map中记录原节点与新节点的映射关系。(注意每次都必须new Node)
  2. 第二次遍历,添加上新节点的next和random
    代码实现如下:
class Solution {
    public Node copyRandomList(Node head) {
        Node pre = head;
        HashMap<Node, Node> map = new HashMap<>();
        while(pre != null) {
            map.put(pre, new Node(pre.val));
            pre = pre.next;           
        }
        pre = head;
        while(pre!= null) {
            map.get(pre).next = map.get(pre.next);
            map.get(pre).random = map.get(pre.random);
            pre = pre.next;
        }
        return map.get(head);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值