# 138. Copy List with Random Pointer

lpy1990
A linked list is given such that each node contains an additional
random pointer which could point to any node in the list or null.

Return a deep copy of the list.

## HashMap法

### 代码

``````public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
}
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode node = head.next;
RandomListNode pre = newHead;
while (node != null) {
RandomListNode tmp = new RandomListNode(node.label);
map.put(node, tmp);
pre.next = tmp;
node = node.next;
pre = pre.next;
}
while (node != null) {
pre.random = map.get(node.random);
node = node.next;
pre = pre.next;
}
}
}``````

## 复制链表法

### 代码

``````public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
}
RandomListNode node = head;
while (node != null) {
RandomListNode tmp = new RandomListNode(node.label);
tmp.next = node.next;
node.next = tmp;
node = node.next.next;
}
while (node != null) {
if (node.random != null) {
node.next.random = node.random.next;
}
node = node.next.next;
}
while (node != null) {
RandomListNode tmp = node.next;
node.next = tmp.next;
if (tmp.next != null) {
tmp.next = tmp.next.next;
}
node = node.next;
}