struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
typedef pair<RandomListNode *, RandomListNode *> PAIR;
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) {
return nullptr;
}
cloneRandomList(&head);
PAIR pir = splitRandomList(head);
head = pir.first;
return pir.second;
}
void cloneRandomList(RandomListNode **head) {
RandomListNode *pNode = *head;
while (pNode != NULL) {
RandomListNode *tNode = new RandomListNode(pNode->label);
tNode->next = pNode->next;
pNode->next = tNode;
pNode = tNode->next;
}
makeRandomList(&(*head));
}
void makeRandomList(RandomListNode **head) {
RandomListNode *pNode = *head;
while (pNode != NULL) {
if (pNode->random != NULL) {
pNode->next->random = pNode->random->next;
}
pNode = pNode->next->next;
}
}
PAIR splitRandomList(RandomListNode *head) {
RandomListNode *newHead = head->next;
RandomListNode *headA, *headB;
headA = head;
headB = newHead;
while (head != NULL) {
head->next = newHead->next;
head = newHead->next;
if (head != NULL) {
newHead->next = head->next;
newHead = head->next;
}
}
return{ headA, headB };
}
};