leetcode 138
HashMap <Node,Node> map = new HashMap<>();
public Node copyRandomList(Node head) {
if(head==null) return null;
if(map.containsKey(head)) return map.get(head);
Node node = new Node(head.val);
map.put(head,node);
node.next = copyRandomList(head.next);
node.random = copyRandomList(head.random);
return node;
}
HashMap <Node,Node> map = new HashMap<>();
public Node clone(Node head){
if(head==null) return null;
if(map.containsKey(head)) return map.get(head);
else{
Node node = new Node(head.val);
map.put(head,node);
return node;
}
}
public Node copyRandomList(Node head) {
if(head==null) return null;
Node node = new Node(head.val);
Node old = head;
map.put(old,node);
while(old!=null){
node.next=clone(old.next);
node.random=clone(old.random);
node = node.next;
old = old.next;
}
return map.get(head);
}
public Node copyRandomList(Node head) {
if(head==null) return null;
Node h = head;
Node ptr;
while(h!=null){
ptr = new Node(h.val);
ptr.next = h.next;
h.next = ptr;
h = h.next.next;
}
h = head;
while(h!=null){
h.next.random = (h.random == null)?null:h.random.next;
h = h.next.next;
}
h = head;
ptr = head.next;
Node p = ptr;
while(h!=null){
h.next = ptr.next;
ptr.next = (ptr.next == null)?null:ptr.next.next;
h = h.next;
ptr = ptr.next;
}
return p;
}