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;
        }
    }
    

      

  • 相关阅读:
    python 之 xlrd模块 excel的读使用
    将str文本类型转换为dict
    pycharm快捷键、常用设置、配置管理
    Bye bye bye
    课题一--作业复习
    python 整齐输出与编码读写
    图像分割——并行区域技术
    主动轮廓模型(重点)
    边界技术
    二阶导数算子
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3565856.html
Copyright © 2011-2022 走看看