> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/linked-list/138.-copy-list-with-random-pointer.md).

# 138. 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**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list.

**Example 1:**

![](https://discuss.leetcode.com/uploads/files/1470150906153-2yxeznm.png)

```
Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
```

**Note:**

1. You must return the **copy of the given head** as a reference to the cloned list.

```cpp
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node() {}

    Node(int _val, Node* _next, Node* _random) {
        val = _val;
        next = _next;
        random = _random;
    }
};
```

```cpp
// Iteration + Hash table
Node* copyRandomList(Node* head) { // time: O(n); space: O(n)
    if (!head) return nullptr;
    unordered_map<Node*, Node*> m;
    Node* cur = head;
    // Copy each node
    while (cur) {
        m[cur] = new Node(cur->val, nullptr, nullptr);
        cur = cur->next;
    }
    // Assign next and random node pointers
    cur = head;
    while (cur) {
        m[cur]->next = m[cur->next];
        m[cur]->random = m[cur->random];
        cur = cur->next;
    }
    return m[head];
}
```

```cpp
// Recursion + Hash table
unordered_map<Node*, Node*> m;
Node* copyRandomList(Node* head) { // time: O(n); space: O(n)
    if (!head) return nullptr;
    if (m[head]) return m[head];
    Node* node = new Node(head->val, nullptr, nullptr);
    m[head] = node;
    node->next = copyRandomList(head->next);
    node->random = copyRandomList(head->random);
    return node;
}
```

```cpp
// Constant space
Node* copyRandomList(Node* head) { // time: O(n); space: O(1)
    if (!head) return nullptr;
    Node *cur = head, *next = nullptr;
    // Copy each node and append each node to its original node
    while (cur) {
        next = cur->next;
        Node* node = new Node(cur->val, nullptr, nullptr);
        cur->next = node;
        node->next = next;
        cur = next;
    }
    // Assign random Node pointers
    cur = head;
    while (cur) {
        if (cur->random) {
            cur->next->random = cur->random->next;
        }
        cur = cur->next->next;
    }
    // Separate original and duplicate lists
    cur = head;
    
    // Node* res = cur->next;
    // while (cur) {
    //     Node* next = cur->next;
    //     cur->next = next->next;
    //     if (next->next) next->next = next->next->next;
    //     cur = cur->next;
    // }
    // return res;
    
    Node *dummy = new Node(-1e7, nullptr, nullptr), *pre = dummy;
    while (cur) {
        next = cur->next;
        pre->next = next;
        pre = pre->next;
        cur->next = next->next;
        cur = cur->next;
    }
    Node* res = dummy->next;
    delete dummy;
    return res;
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/linked-list/138.-copy-list-with-random-pointer.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
