zoukankan      html  css  js  c++  java
  • Copy List with Random Pointer

     1 /**
     2  * Definition for singly-linked list with a random pointer.
     3  * class RandomListNode {
     4  *     int label;
     5  *     RandomListNode next, random;
     6  *     RandomListNode(int x) { this.label = x; }
     7  * };
     8  */
     9 public class Solution {
    10     public RandomListNode copyRandomList(RandomListNode head) {
    11         HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
    12         RandomListNode fakehead = new RandomListNode(0);
    13         RandomListNode runner = head;
    14         RandomListNode newrunner = fakehead;
    15         
    16         while(runner!=null){
    17             RandomListNode node = null;
    18             if(map.containsKey(runner)){
    19                 node = map.get(runner);
    20             }
    21             else{
    22                 node = new RandomListNode(runner.label);
    23                 map.put(runner, node);
    24             }
    25             newrunner.next = node;
    26             
    27             if(runner.random!=null){
    28                 if(map.containsKey(runner.random)){
    29                     node = map.get(runner.random);
    30                 }
    31                 else{
    32                     node = new RandomListNode(runner.random.label);
    33                     map.put(runner.random, node);
    34                 }
    35                 newrunner.next.random = node;
    36             }
    37             newrunner = newrunner.next;
    38             runner = runner.next;
    39         }
    40         return fakehead.next;
    41     }
    42 }
  • 相关阅读:
    正则表达式
    iOS获取设备型号、设备类型等信息
    Dubbo-Zookeeper安装
    CentOS-常用安装
    多线程-线程通信
    JVM-高效并发
    静态代理与JDK动态代理
    JVM-类加载机制
    RPC原理及实现
    JVM-自动内存管理机制
  • 原文地址:https://www.cnblogs.com/jasonC/p/3452433.html
Copyright © 2011-2022 走看看