A linked list is given such that each node contains an additional random pointer which cocould point to any node in the list or null.
Return a deep copy of the list.
/*** Definition for singly-linked list with a random pointer. * struct randomlistnode {* int label; * randomlistnode * Next, * random; * randomlistnode (int x): Label (x), next (null), random (null) {} *}; */struct randomlistnode {int label; randomlistnode * Next, * random; randomlistnode (int x): Label (x), next (null), random (null) {}}; class solution {public: randomlistnode * copyrandomlist (randomlistnode * Head) {If (Head = NULL) return head; // insert a newnode. randomlistnode * oldlistnode = head after each oldlist node. While (oldlistnode! = NULL) {randomlistnode * newlistnode = new randomlistnode (oldlistnode-> label); newlistnode-> next = oldlistnode-> next; newlistnode-> random = oldlistnode-> random; oldlistnode-> next = newlistnode; oldlistnode = oldlistnode-> next;} // update the node associated with the random node on newlistnode oldlistnode = head; while (oldlistnode! = NULL) {If (oldlistnode-> random! = NULL) {oldlistnode-> next-> random = oldlistnode-> random-> next;} oldlistnode = oldlistnode-> next ;} // separate oldlistnode from newlistnoderandomlistnode * newlistnode = new randomlistnode (0); newlistnode-> next = head; oldlistnode = head; randomlistnode * resultlistnode = newlistnode; while (oldlistnode! = NULL) {newlistnode-> next = oldlistnode-> next; oldlistnode-> next = newlistnode-> next; newlistnode = newlistnode-> next; oldlistnode = oldlistnode-> next;} return resultlistnode-> next ;}};
Leetcode-copy list with random pointer