class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head==NULL)
return NULL;
RandomListNode *cur=head;
RandomListNode *newHead=NULL;
while(cur!=NULL)
{
RandomListNode *p=new RandomListNode(cur->label);
p->next=cur->next;
cur->next=p;
cur=p->next;
}
cur=head;
while(cur!=NULL)
{
if(cur->random!=NULL)
{
cur->next->random=cur->random->next;
cur=cur->next->next;
}
else
{
cur=cur->next->next;
}
}
cur=head;
newHead=cur->next;
RandomListNode * newcur=newHead;
cur->next = cur->next->next;
cur=cur->next;
while(cur!=NULL)
{
newcur->next=cur->next;
newcur=newcur->next;
cur->next=cur->next->next;
cur=cur->next;
}
newcur->next=NULL;
return newHead;
}
};
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head==NULL)
return NULL;
RandomListNode *cur=head;
RandomListNode *newHead=NULL;
while(cur!=NULL)
{
RandomListNode *p=new RandomListNode(cur->label);
p->next=cur->next;
cur->next=p;
cur=p->next;
}
cur=head;
while(cur!=NULL)
{
if(cur->random!=NULL)
{
cur->next->random=cur->random->next;
cur=cur->next->next;
}
else
{
cur=cur->next->next;
}
}
cur=head;
newHead=cur->next;
RandomListNode * newcur=newHead;
cur->next = cur->next->next;
cur=cur->next;
while(cur!=NULL)
{
newcur->next=cur->next;
newcur=newcur->next;
cur->next=cur->next->next;
cur=cur->next;
}
newcur->next=NULL;
return newHead;
}
};