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

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
     
     /* 
       create a hashmap store <oldNode, newNode>
       copy value and next to new list
       copy random node in hashmap for new list
     */
    public class Solution {
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head == null) return null;
            RandomListNode newhead = new RandomListNode(head.label);
            RandomListNode newl = newhead;
            RandomListNode oldl = head.next;
            HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
            map.put(head, newhead);
            while(oldl != null){
                RandomListNode newNode = new RandomListNode(oldl.label);
                map.put(oldl, newNode);
                newl.next = newNode;
                
                oldl = oldl.next;
                newl = newl.next;
            }
            
            oldl = head;
            newl = newhead;
            while(oldl != null){
                newl.random = map.get(oldl.random);
                
                newl = newl.next;
                oldl = oldl.next;
            }
            return newhead;
        }
    }
  • 相关阅读:
    centos 7 install
    sbt
    maven create project
    java异常个人理解
    (poj1094)Sorting It All Out
    stars
    Following Orders(拓扑排序)
    The House Of Santa Claus(dfs)
    Prime Path(bfs)
    Fence Repair(优先队列容器的应用)
  • 原文地址:https://www.cnblogs.com/joannacode/p/6108706.html
Copyright © 2011-2022 走看看