要求:除了next还有一个随机指针,复制
思路:
法一:递归创建
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
map<Node*,Node*> old_new;
Node* copyRandomList(Node* head) {
if(!head)return nullptr;
if(old_new.count(head)==0){
Node* newhead=new Node(head->val);
old_new[head]=newhead;
newhead->next=copyRandomList(head->next);
newhead->random=copyRandomList(head->random);
}
return old_new[head];
}
};
法二:A-A*-B-B*,然后连接random,然后拆掉,为了random只能旧的放前面,细节太容易出错
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head)return nullptr;
Node* oldnode=head;
Node* newnode;
while(oldnode){
newnode=new Node(oldnode->val);
newnode->next=oldnode->next;
oldnode->next=newnode;
oldnode=newnode->next;
}
oldnode=head;
newnode=head->next;
while(oldnode){
if(oldnode->random)newnode->random=oldnode->random->next;
oldnode=oldnode->next->next;
if(oldnode)newnode=newnode->next->next;
}
oldnode=head;
newnode=head->next;
Node* ans=newnode;
while(oldnode){
oldnode->next=newnode->next;
oldnode=oldnode->next;
if(oldnode){
newnode->next=oldnode->next;
newnode=newnode->next;
}
}
return ans;
}
};