https://leetcode.com/problems/copy-list-with-random-pointer/
链表的一些trick
个人解答
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
# duplicate each node, insert behind
p = head
while p:
nxt = p.next
p.next = Node(p.val, nxt)
p = nxt
# random pointer
p = head
while p and p.next:
curr = p.next
nxt = curr.next
curr.random = p.random.next if p.random else None
p = nxt
# next pointer
p = head
while p and p.next and p.next.next:
curr = p.next
nxt = curr.next
curr.next = nxt.next
p = nxt
return 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 = head
q = dummy
while p:
q.next = Node(p.val)
nodeMap[p] = q.next
p = p.next
q = q.next
p = head
q = dummy.next
while p:
q.random = nodeMap[p.random] if p.random else None
p = p.next
q = q.next
return dummy.next