Copy List with Random Pointer LeetCode solution in C++
1class Solution {2public:3Node *copyRandomList(Node *head) {4if (head == NULL) {5return NULL;6}78Node *temp = head;9while (temp != NULL) {10Node *m = new Node(temp->val);11m->next = temp->next;12temp->next = m;13temp = temp->next->next;14}15temp = head;16while (temp != NULL) {17if (temp->random == NULL) {18temp->next->random = NULL;19} else {20temp->next->random = temp->random->next;21}2223temp = temp->next->next;24}25temp = head;26Node *p = new Node(-1);27Node *r = p;28Node *q = head;29while (q != NULL) {30q = q->next->next;31p->next = temp->next;32p = p->next;33temp->next = q;34temp = temp->next;35}36p->next = NULL;3738return r->next;39}40};