哈希表法;
- 复制单链表,并将新旧链表存入哈希表中;
- 遍历哈希表,复制每个结点的随即指针;
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
if(pHead == NULL) return NULL;
//添加头部节点;
RandomListNode* res = new RandomListNode(0);
unordered_map<RandomListNode*,RandomListNode*> map;
RandomListNode* cur = pHead;
RandomListNode* pre = res;
//遍历源列表;复制链表的节点,并建立新旧链表的映射;
while(cur != NULL){
RandomListNode* newNode = new RandomListNode(cur->label);
map[cur] = newNode;
//连接
pre->next = newNode;
pre = pre->next;
//遍历;
cur = cur->next;
}
//遍历哈希表,复制随机指针;
for(auto node:map){
if(node.first->random == NULL)
node.second->random = NULL;
else
node.second->random = map[node.first->random];
}
return res->next;
}
};