/** * Definition for singly-linked list with a random pointer. * struct ListNode { * int val; * ListNode *next, *random; * ListNode(int x) : val(x), next(NULL), random(NULL) {} * }; */ classSolution { public: ListNode *copyRandomList(ListNode *head){
if (!head) returnnullptr;
ListNode *ans, *ans_h, *t;
t = head; ans_h = ans = newListNode(t -> val);
while (t && t -> next) { t = t -> next; ans -> next = newListNode(t -> val); ans = ans -> next; }
t = head; ans = ans_h;
while (t) { auto* random = t -> random; if (random) { auto *temp = head, *ans_t = ans_h; while (temp != random) { temp = temp -> next; ans_t = ans_t -> next; } ans -> random = ans_t; } t = t -> next; ans = ans -> next; }