# 138. Copy List with Random Pointer

## 1.問題

* 一個linked list中每個node除了next之外, 有個random指針會隨機指向list中的任一node, 回傳這個list的deep copy

![](/files/-LNYHcLn2Il4gyKemcG-)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
* function header, parameter
* test input
* 觀察
  * 用map儲存已經複製過的node, 避免重複拷貝, 重複走訪
* 說明想法
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        unordered_map<RandomListNode *, RandomListNode *> m;
        return getCopyNode(head, m);
    }
private:
    RandomListNode * getCopyNode(RandomListNode *head, unordered_map<RandomListNode*, RandomListNode*>& m) {
        if (!head) {
            return NULL;
        }
        if (m.find(head) != m.end()) {
            return m[head];
        }
        
        RandomListNode * node = new RandomListNode(head->label);
        m[head] = node;
        node->next = getCopyNode(head->next, m);
        node->random = getCopyNode(head->random, m);
        return node;
    }
};
```


---

# Agent Instructions: 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://jenhsuan.gitbook.io/algorithm/leetcode/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.
