# LeetCode：138. 複製帶隨機指針的鏈表

### 三、代碼實現

``````/*
// 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;
}
};
*/
class Solution {
public:
}
map<Node*, Node*> map;
//1. 遍歷鏈表，將原節點作爲key，拷貝節點作爲value保存在map中
while (cur != nullptr) {
//原來是1->2->3->4,現在map中存入的是[1,1],[2,2],[3,3],[4,4]
Node *copy = new Node(cur->val);
map[cur] = copy;
cur = cur->next;
}
//2. 複製鏈表next和random指針
//1的random是3;2和3的爲空;4的是2
while (cur != nullptr) {//以1爲例
//1->2
map[cur]->next = map[cur->next];
//1 random->3
map[cur]->random = map[cur->random];
//下一個結點
cur = cur->next;
}
}
};``````

``````class Solution {
public:
}
//1. 將複製節點添加到原節點後面：1->1->2->2->3->3->4->4
while (node != nullptr) {
Node *copy = new Node(node->val, nullptr, nullptr);
copy->next = node->next;
node->next = copy;
node = copy->next;
}

//2. 複製random節點
while (node != nullptr) {
if (node->random != nullptr) {//以1爲例
//第二個1指向3
node->next->random = node->random->next;
}
//走兩步
node = node->next->next;
}

//3. 分離鏈表（將鏈表斷開成1->2->3->4,此時之前第二個1、2、3、4都已經爲random了）
while (node != nullptr) {
node->next = node->next->next;
if (newNode->next != nullptr) {
newNode->next = newNode->next->next;
}
node = node->next;
newNode = newNode->next;
}