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;
        }
    }
  • 相关阅读:
    Android studio 中国的垃圾问题解决
    实现一个简单的boot
    代理下载android4.4源代码
    《程序员在第一季度追姐姐的书》——提升自己的形象气质
    第46周四
    Spring单例与线程安全小结
    2014第46周二
    第46周一
    第45周日
    第45周六
  • 原文地址:https://www.cnblogs.com/joannacode/p/6108706.html
Copyright © 2011-2022 走看看