Last updated
Was this helpful?
Last updated
Was this helpful?
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
深度copy每个结点带有随机指针的列表,随机指针可指向列表中任意结点。深copy都是先建立起新节点和旧结点的一一映射,然后再去完善它们内部关系。Random pointer有一种很巧妙的解法,就是把复制出来的节点放在原节点旁(next)一一串起来。再重头遍历,每个节点的cp节点的random就是原节点random的next。再重头遍历,把cp节点依次串起来。
TC: O(n), SC: O(n)
还有SC O(1)的解法:
把每个复制出来的结点和原结点紧挨着放在一个list里,这样找到原结点的random就能定位到新结点的random。
https://leetcode.com/problems/copy-list-with-random-pointer/description/