给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深度拷贝。
Java代码:
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (null == head)
return null;
RandomListNode p = head.next, result = new RandomListNode(head.label), q = result;
Map<RandomListNode, RandomListNode> map = new HashMap<>(), link = new HashMap<>();
link.put(head, result);
if (null != head.random)
map.put(head, result);
while (null != p) {
RandomListNode tmp = new RandomListNode(p.label);
q.next = tmp;
link.put(p, tmp);
if (null != p.random)
map.put(p, tmp);
p = p.next;
q = q.next;
}
for (RandomListNode r : map.keySet()) {
map.get(r).random = link.get(r.random);
}
return result;
}
}