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 }
  • 相关阅读:
    LRU算法简介
    linux下安装nginx+php+mysql环境 详细教程
    CentOS 6.6编译安装Nginx1.6.2+MySQL5.6.21+PHP5.6.3
    unicode 格式 转汉字
    js 操作cookie
    哈希函数
    php商城秒杀活动
    php 栈、 出栈、入栈
    php单例模式
    封装PHP增删改查方法
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/11124141.html
Copyright © 2011-2022 走看看