方法1:
先将节点放入vector中,先连接好每个节点的random。
class Solution {
public:
int getNum(RandomListNode* head,RandomListNode* p)
{
if(p==NULL)
return -1;
int cnt=1;
RandomListNode* ph=head;
while(ph&&p!=ph)
{
ph=ph->next;
cnt++;
}
return cnt;
}
void SetRandom(vector<RandomListNode*>& vec,RandomListNode* p,int cnt)
{
if(cnt==-1)
{
p->random=NULL;
return;
}
int _size=vec.size();
int len=cnt;
while(len>_size)
{
RandomListNode* p=new RandomListNode(INT_MAX);
vec.push_back(p);
len--;
}
p->random=vec[cnt-1];
}
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode* Head=NULL,*pre=Head;
RandomListNode* cur=head;
if(head==NULL)
return Head;
vector<RandomListNode*> vec;
int i=1;
while(cur)
{
if(vec.size()<i)
{
RandomListNode *p=new RandomListNode(cur->label);
vec.push_back(p);
int cnt=getNum(head, cur->random);
SetRandom(vec,p,cnt);
}
else
{
vec[i-1]->label=cur->label;
int cnt=getNum(head, cur->random);
SetRandom(vec,vec[i-1],cnt);
}
cur=cur->next;
i++;
}
int _size=vec.size();
Head=vec[0];
pre=Head;
for(i=1;i<_size;i++)
{
pre=pre->next=vec[i];
}
pre->next=NULL;
return Head;
}
};
方法2:
使用哈希表unordered_map
还可以轻松拷贝带环的list
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head==NULL)
return NULL;
unordered_map<RandomListNode*, RandomListNode*> mp;
RandomListNode *Head=new RandomListNode(head->label),*pre=Head,*cur=head;
mp[cur]=pre;
while(cur->next)
{
RandomListNode* p=new RandomListNode(cur->next->label);
if(mp.find(cur->next)==mp.end())
mp[cur->next]=p;
else
break;
pre=pre->next=p;
cur=cur->next;
}
RandomListNode* sta=NULL;
if(cur->next==NULL)
pre->next=NULL;
else
pre->next=sta=cur->next;
cur=head;
int cnt=0;
while(cur)
{
RandomListNode* p=cur->random;
if(p==NULL)
{
mp[cur]->random=NULL;
}
else
{
mp[cur]->random=mp[p];
}
cur=cur->next;
if(cur==sta)
cnt++;
if(cnt>=2)
break;
}
return Head;
}
};