问题描述: 复制带随机指针的链表
- 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
- 要求返回这个链表的 深拷贝。
STL Map的使用
int main() {
map<Node*, int> node_map;
Node a(5);
Node b(3);
Node c(6);
a.next = &b;
b.next = &c;
a.random = &c;
b.random = &a;
c.random = &c;
node_map[&a] = 1; // 将a的地址映射为1
node_map[&b] = 2; // 将b的地址映射为2
node_map[&c] = 3; // 将c的地址映射为3
cout << "a的random指针指向:" << node_map[a.random] << endl;
cout << "b的random指针指向:" << node_map[b.random] << endl;
cout << "c的random指针指向:" << node_map[c.random] << endl;
return 0;
}
结果:
a的random指针指向:3
b的random指针指向:1
c的random指针指向:3
解决深拷贝的算法:
// 算法写在一个类里
class Solution {
public:
Node* copyRandomList(Node* head) {
map<Node*, int> node_map;
// 用vector储存新的链表结点,而vector类似数组有id值便于下面的操作
vector<Node*> node_vec;
Node* ptr = head;
int i = 0;
while (ptr)
{
node_vec.push_back(new Node(ptr->val));
node_map[ptr] = i;
ptr = ptr->next;
i++;
}
node_vec.push_back(0);
ptr = head;
i = 0;
while (ptr) {
node_vec[i]->next = node_vec[i + 1];
if (ptr->random)
{
int id = node_map[ptr->random]; // 根据random找出map对应的id
node_vec[i]->random = node_vec[id]; // 根据id在vector里找出该结点
}
ptr = ptr->next;
i++;
}
return node_vec[0];
}
};
ps: 教程 https://www.bilibili.com/video/BV1GW411Q77S?t=7029&p=2 的笔记
LeetCode题号: 138