package com.heu.wsq.leetcode.inoffer;
import java.util.HashMap;
import java.util.Map;
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public class Offer35 {
public Node copyRandomList(Node head) {
Node root = null;
Node q = head;
Map<Node, Node> map = new HashMap<>();
while(q != null){
if(!map.containsKey(q)){
map.put(q, new Node(q.val));
}
Node tmp = map.get(q);
if(q.next != null){
if(!map.containsKey(q.next)){
map.put(q.next, new Node(q.next.val));
}
tmp.next = map.get(q.next);
}
if(q.random != null){
if(!map.containsKey(q.random)){
map.put(q.random, new Node(q.random.val));
}
tmp.random = map.get(q.random);
}
if(root == null){
root = tmp;
}
q = q.next;
}
return root;
}
}