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 }