/** * 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) returnNULL; for (auto p = head; p;) { auto np = new ListNode(p->val); auto next = p->next; np->next = next; p->next = np; p = next; } for (auto p = head; p; p = p->next->next) { if (p->random) { p->next->random = p->random->next; } } auto dummy = new ListNode(-1); auto tail = dummy; for (auto p =head; p;) { tail = tail->next = p->next; p = p->next = p->next->next; } return dummy->next; } };