https://leetcode.com/problems/copy-list-with-random-pointer/
链表的一些trick
个人解答
class Solution:def copyRandomList(self, head: 'Node') -> 'Node':# duplicate each node, insert behindp = headwhile p:nxt = p.nextp.next = Node(p.val, nxt)p = nxt# random pointerp = headwhile p and p.next:curr = p.nextnxt = curr.nextcurr.random = p.random.next if p.random else Nonep = nxt# next pointerp = headwhile p and p.next and p.next.next:curr = p.nextnxt = curr.nextcurr.next = nxt.nextp = nxtreturn head.next if head else None
题目分析
最简单的思路,用hash table存
如果不想用额外的空间,就需要充分利用原先链表的特性。
比如,新加入的节点先放到原节点的后边,更新完random之后,再更新next。
其它解法
naive的hash table解法
class Solution:def copyRandomList(self, head: 'Node') -> 'Node':nodeMap = {}dummy = Node(0)p = headq = dummywhile p:q.next = Node(p.val)nodeMap[p] = q.nextp = p.nextq = q.nextp = headq = dummy.nextwhile p:q.random = nodeMap[p.random] if p.random else Nonep = p.nextq = q.nextreturn dummy.next
