/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead == NULL)
return pHead;
cloneNext(pHead);
cloneRandom(pHead);
pHead = separate(pHead);
return pHead;
}
private:
void cloneNext(RandomListNode* head){
while(head != NULL){
RandomListNode* temp = new RandomListNode(head->label);
temp->next = head->next;
head->next = temp;
head = temp->next;
}
}
void cloneRandom(RandomListNode* head){
while(head != NULL){
if(head->random != NULL)
head->next->random = head->random->next;
head = head->next->next;
}
}
RandomListNode* separate(RandomListNode* head){
RandomListNode* temp = head->next;
RandomListNode* newHead = head->next;
while(newHead->next != NULL){
head->next = newHead->next;
newHead->next = newHead->next->next;
head = head->next;
newHead = newHead->next;
}
head->next = NULL;
return temp;
}
};