# LeetCode Copy List with Random Pointer

LeetCode Copy List with Random Pointer

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.

```class Solution {
public:
unordered_map<RandomListNode*, int> hash;
vector<RandomListNode*> array_for_list;
int idx = 0;
while (h1) {
hash[h1] = idx++;
RandomListNode *node = new RandomListNode(h1->label);
array_for_list.push_back(node);
h2->next = node;
h1 = h1->next;
h2 = h2->next;
}
while (h1) {
if (h1->random) {
h2->random = array_for_list[hash[h1->random]];
}
h1 = h1->next;
h2 = h2->next;
}
}
};
```

```class Solution {
public:
while (iter) {
RandomListNode *node = new RandomListNode(iter->label);
node->next = iter->next;
iter->next = node;
iter = node->next;
}

while (iter) {
if (iter->random) {
iter->next->random = iter->random->next;
}
iter = iter->next->next;
}

RandomListNode *copy_head = new RandomListNode(0); // dummy
RandomListNode *copy_iter = iter->next, *copy_tail = copy_head;
while (iter) {
copy_tail->next = copy_iter;
copy_tail = copy_tail->next;

iter->next = copy_iter->next;
iter = iter->next;

if (iter) {
copy_iter->next = iter->next;
copy_iter = copy_iter->next;
}
}