# [138\. Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) :::spoiler Solution ```cpp= /* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { private: unordered_map<Node*, Node*> oldToNew; public: Node* copyRandomList(Node* head) { return dfs(head); } Node* dfs(Node* node) { if (!node) return nullptr; if (oldToNew.count(node)) return oldToNew[node]; // 如果沒有找到 node oldToNew[node] = new Node(node->val); oldToNew[node]->next = dfs(node->next); oldToNew[node]->random = dfs(node->random); return oldToNew[node]; } }; ``` - 時間複雜度:$O(N)$ - 空間複雜度:$O(N)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up