Node* copyRandomList(Node* head){
if(!head) return nullptr;
Node* ptr = head;
while(ptr){
Node* newNode = new Node(ptr->val,nullptr,nullptr);
newNode->next = ptr->next;
ptr->next = newNode;
ptr = newNode->next;
}
ptr = head;
while(ptr){
ptr->next->random = (ptr->random!=nullptr)?ptr->random->next:nullptr;
ptr = ptr->next->next;
}
Node* oldList = head;
Node* newList = head->next;
Node* newHead = head->next;
while(oldList){
oldList->next = oldList->next->next;
newList->next = (newList->next!=nullptr)?newList->next->next:nullptr;
oldList = oldList->next;
newList = newList->next;
}
return newHead;
}
递归
class Solution {
public:
unordered_map<Node*,Node*> visited;
Node* copyRandomList(Node* head) {
if(!head) return nullptr;
if(visited.find(head)!=visited.end())
return visited[head];
Node* node = new Node(head->val,nullptr,nullptr);
visited[head]=node;
node->next=copyRandomList(head->next);
node->random=copyRandomList(head->random);
return node;
}
};
迭代
/*
// 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:
unordered_map<Node*,Node*> visited;
Node* getClonedNode(Node* node){
if(node){
if(visited.find(node)!=visited.end()){
return visited[node];
}else{
Node* newNode = new Node(node->val,nullptr,nullptr);
visited[node]=newNode;
return newNode;
}
}
return nullptr;
}
Node* copyRandomList(Node* head){
if(!head) return nullptr;
Node* oldNode = head;
Node* newNode = new Node(oldNode->val,nullptr,nullptr);
visited[oldNode]=newNode;
while(oldNode){
newNode->random = getClonedNode(oldNode->random);
newNode->next = getClonedNode(oldNode->next);
oldNode = oldNode->next;
newNode = newNode->next;
}
return visited[head];
}
};