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.
思路:用map存储自己和拷贝,今天看到基友的代码,风格很好,反观自己,代码很拙劣。所以在后续的编程中药保持良好的代码风格。
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return nullptr;
RandomListNode *myHead = new RandomListNode(head->label);
RandomListNode *cur = head;
RandomListNode *myCpoy = myHead;
unordered_map<RandomListNode*, RandomListNode*> visited;
visited[head] = myHead;
while (cur){
if (!cur->next){
myCpoy->next = nullptr;
}
else if (visited.find(cur->next) == visited.end()){ //
RandomListNode * myNext = new RandomListNode(cur->next->label);
visited[cur->next] = myNext;
myCpoy->next = myNext;
}
else{
myCpoy->next = visited[cur->next];
}
if (!cur->random){
myCpoy->random = nullptr;
}
else if (visited.find(cur->random) == visited.end()){
RandomListNode *myRandom = new RandomListNode(cur->random->label);
visited[cur->random] = myRandom;
myCpoy->random = myRandom;
}
else{
myCpoy->random = visited[cur->random];
}
cur = cur->next;
myCpoy = myCpoy->next;
}
return myHead;
}
};