I have a singly linked list. Apart from the normal “Next” pointer, there is one more pointer(random ptr) in each node which points to some random node of the list. How to create a clone of such a list? (In less than O(n^2)).
Any suggestion or solution using Java?
Here is an answer in O(n) time and O(1) space.
(Solutions with a hashtable or association map need O(n) space).
shg’s link is also a solution in O(n) time and O(1) space.
tof size n, each cell consisting of two pointersaandb. At the end of the algorithm, this will be the copy. But it isn’t for now.kth cellcof the original list:t[k].abe a pointer tocc.nextbe a pointer tot[k](the original list is temporarily destroyed, we will restore it later.). We can now follow pointers back and forth between the original list andt.c, letc.next.bbe a pointer toc.random.next. (c.nextis a cell int, so isc.random.next). This way, thebfields of the cells intare a copy of the structure of therandompointers in the original list.k, lett[k].a.nextpoint tot[k+1].a.nextta linked list: for eachk, lett[k].apoint tot[k+1].As opposed to shg’s link, this solution has the drawback of requiring a continuous block of size n in memory.