138. 随机链表的复制

自己做

解:哈希表
java
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Node p = head;
Node res = new Node(0);
Node q = res;
List<Node> list = new ArrayList();
Map<Node, Integer> hash1 = new HashMap();
int i = 0;
//根据next复制链表
while(p != null){
q.next = new Node(p.val);
q = q.next;
hash1.put(p, i);
list.add(q);
p = p.next;
i++;
}
//建立random
p = head;
q = res.next;
while(p != null){
if(p.random != null)
q.random = list.get(hash1.get(p.random));
else
q.random = null;
p = p.next;
q = q.next;
}
return res.next;
}
}
