• [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 }
  • 相关阅读:
    某个周六加班日的划水记
    如何保证消息的可靠性传输
    PHP面向对象学习六 多态
    PHP面向对象学习五 类中接口的应用
    PHP面向对象学习四 类的关键字
    PHP面向对象学习三 类的抽象方法和类
    PHP面向对象学习二
    PHP面向对象学习一
    高级ql
    mysql 方法
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/11124141.html
Copyright © 2020-2023  润新知