zoukankan      html  css  js  c++  java
  • leetcode--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.

    Have you been asked this question in an interview? 

    Discuss

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            RandomListNode newHead = new RandomListNode(0);
            Map<RandomListNode, RandomListNode> oldToNew = new HashMap<RandomListNode, RandomListNode>();
            Map<RandomListNode, RandomListNode> newToOld = new HashMap<RandomListNode, RandomListNode>();
            if(head != null){
                RandomListNode nextNode = head;
                RandomListNode nextNewNode = newHead;
                while(nextNode != null){
                    nextNewNode.next = new RandomListNode(nextNode.label);
                    nextNewNode = nextNewNode.next;
                    oldToNew.put(nextNode, nextNewNode);
                    newToOld.put(nextNewNode, nextNode);
                    nextNode = nextNode.next;
                }
                nextNewNode.next = null;
                nextNewNode = newHead.next;
                while(nextNewNode != null){
                    RandomListNode tempOld = newToOld.get(nextNewNode);
                    RandomListNode tempnew = oldToNew.get(tempOld.random);
                    nextNewNode.random = tempnew;
                    nextNewNode = nextNewNode.next;
                }
            }
            newHead = newHead.next;
            return newHead;
        }
    }
    

      

  • 相关阅读:
    java中的“指针”
    UEditor1.4.3.3编辑器漏洞
    csrf攻击实例
    shiro java 反序列漏洞复现
    渗透面试问题
    了解 OWASP TOP 10
    网络基础知识回顾
    cs(cobalt strike)的使用
    解决docker-valhub漏洞环境下载慢的问题
    Vulhub漏洞CVE-2017-10271复现
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3565856.html
Copyright © 2011-2022 走看看