zoukankan      html  css  js  c++  java
  • [leetcode]138. Copy List with Random Pointer复制带随机指针的链表

    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.

    Example 1:

    Input:
    {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
    
    Explanation:
    Node 1's value is 1, both of its next and random pointer points to Node 2.
    Node 2's value is 2, its next pointer points to null and its random pointer points to itself.

    Note:

    1. You must return the copy of the given head as a reference to the cloned list.

    题意

    给定一个单链表,链表中的每个节点包含一个额外的指针,随机指向链表中的其它节点或者指向 null。请复制整个链表,并返回新链表的头结点。

    思路

    1、 copy nodes:HashMap存入每个 node 和 new node(deep copy后的)

    2、 link  nodes: 扫一遍原链表, 将每个node的next和random关系link起来

    代码

     1 /*
     2 // Definition for a Node.
     3 class Node {
     4     public int val;
     5     public Node next;
     6     public Node random;
     7 
     8     public Node() {}
     9 
    10     public Node(int _val,Node _next,Node _random) {
    11         val = _val;
    12         next = _next;
    13         random = _random;
    14     }
    15 };
    16 */
    17 class Solution {
    18       public Node copyRandomList(Node head) {
    19         if (head == null) return null;
    20 
    21         Map<Node, Node> map = new HashMap<>();
    22 
    23         //copy all the nodes
    24         Node node = head;
    25         while (node != null) {
    26             map.put(node, new Node(node.val, node.next, node.random));
    27             node = node.next;
    28         }
    29 
    30         // assign next and random pointers
    31         node = head;
    32         while (node != null) {
    33             map.get(node).next = map.get(node.next);
    34             map.get(node).random = map.get(node.random);
    35             node = node.next;
    36         }
    37 
    38         return map.get(head);
    39     }
    40 }
  • 相关阅读:
    centos6安装部署ntp
    pttablechecksum和pttablesync修复主从不一致的数据
    clickhouse数据导入导出
    mongodb执行js结果输出文件
    rman验证备份有效性
    使用expdp和impdp进行goldengate初始化
    安装goldengate软件(ogg)
    sql ltrim rtrim
    2022
    Mqtt服务部署
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/11124141.html
Copyright © 2011-2022 走看看