zoukankan      html  css  js  c++  java
  • 138. Copy List with Random Pointer(js)

    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.
    题意:给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点
    代码如下:
    /**
     * // Definition for a Node.
     * function Node(val,next,random) {
     *    this.val = val;
     *    this.next = next;
     *    this.random = random;
     * };
     */
    /**
     * @param {Node} head
     * @return {Node}
     */
    var copyRandomList = function(head) {
       const dummy = new Node(NaN, null, null); 
        let original = head; 
        let copier = dummy; 
    
        const map = new Map();
        while(original) {
            let newNode = new Node(original.val, null, null);
            copier.next = newNode;
            map.set(original, newNode);
            
            copier = copier.next;
            original = original.next;
        }
        copier = dummy.next;
        original = head;
        while(original) {
            if (original.random) {
                copier.random = map.get(original.random)
            }
            copier = copier.next
            original = original.next
        }
        
        return dummy.next
    };
  • 相关阅读:
    LeetCode12: 整数转罗马数字
    LeetCode11:盛最多水的容器
    LeetCode09:判断回文数
    LeetCode08:字符串转换成整数
    LeetCode04:寻找中位数
    LeetCode03:无重复字符的最长子串
    《JAVA编程思想》第四版 PDF 下载 中文版和英文版 高清PDF扫描带书签
    XML
    异常
    委托和匿名方法和Lambda表达式
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10970758.html
Copyright © 2011-2022 走看看