题目:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
法1:哈希表关联容器。
复杂链表的复制涉及到深拷贝,因为除了next指针还有random指针。random指针寻找定位,一般都会考虑到先复制完所有next,然后每个指针的random从头开始遍历。这样时间复杂度太高。O(N^2)
考虑到random指针把两个节点的关系联系了起来,所以思路可以开展到哈希表关联容器上,辅助实现深拷贝。用空间换时间。
unordered_map<node*,node*>mp,
实现的是复制与深拷贝后一一对应的节点。
刚开始的深拷贝,将原先的节点深拷贝后的儿子放入map与其父亲一一对应
mp[t]=new Node(t->val);
next与random指针的复制对应关系!想清楚用unordered_map的实现!
mp[t]->next=mp[t->next];
mp[t]->random=mp[t->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 head;
unordered_map<Node*,Node*>mp;
Node*cur=head;
while(cur)
{
mp[cur]=new Node(cur->val);
cur=cur->next;
}
cur=head;
while(cur)
{
mp[cur]->next=mp[cur->next];
if(cur->random)
mp[cur]->random=mp[cur->random];
cur=cur->next;
}
return mp[head];
}
};
法2.原地复制
比如1->1->3 复制为 1->1->1->1->3->3;
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:
void copyforNext(Node*&head)
{
if(!head) return ;
while(head)
{
Node* temp=new Node(head->val);
temp->next=head->next;
head->next=temp;
head=temp->next;
}
}
void copyforRandom(Node*&head)
{
if(!head) return ;
while(head)
{
Node*temp=head->next;
if(head->random)
{
temp->random=head->random->next;
}
head=temp->next;
}
}
Node* getCopyRES(Node*&head)
{
if(!head) return head;
Node*copyRes=head->next;
Node*tempRes=copyRes;
while(head)
{
head->next=head->next->next;
head=head->next->next;
if(tempRes->next)
{tempRes->next=tempRes->next->next;
tempRes=tempRes->next->next;}
else tempRes->next=NULL;
}
return copyRes;
}
Node* copyRandomList(Node* &head)
{
if(!head) return head;
copyforNext(head);
copyforRandom(head);
return getCopyRES(head);
}
};