A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
该题与clone graph类似,使用一个map保存原链表中的映射
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head == NULL) return NULL;
map<int,RandomListNode *> nodeMap;
set<int> visited;
vector<RandomListNode *> currentLevel, nextLevel;
nodeMap[head->label] = new RandomListNode(head->label);
currentLevel.push_back(head);
while(currentLevel.size() > 0) {
nextLevel.clear();
for(int i = 0; i < currentLevel.size(); i++) {
RandomListNode *one = currentLevel[i];
if(nodeMap.find(one->label) == nodeMap.end()) {
nodeMap[one->label] = new RandomListNode(one->label);
}
visited.insert(one->label);
RandomListNode *tmp = nodeMap[one->label];
RandomListNode *next = one->next;
RandomListNode *ran = one->random;
if(next == NULL) {
tmp->next = NULL;
}else {
if(nodeMap.find(next->label) == nodeMap.end()) {
nodeMap[next->label] = new RandomListNode(next->label);
}
tmp->next = nodeMap[next->label];
if(visited.count(next->label) == 0) {
visited.insert(next->label);
nextLevel.push_back(next);
}
}
if(ran == NULL) {
tmp->random = NULL;
}else {
if(nodeMap.find(ran->label) == nodeMap.end()) {
nodeMap[ran->label] = new RandomListNode(ran->label);
}
tmp->random = nodeMap[ran->label];
if(visited.count(ran->label) == 0) {
visited.insert(ran->label);
nextLevel.push_back(ran);
}
}
}
currentLevel.clear();
currentLevel.assign(nextLevel.begin(),nextLevel.end());
}
return nodeMap[head->label];
}
};