https://leetcode.com/problems/copy-list-with-random-pointer/
链表的一些trick


个人解答

  1. class Solution:
  2. def copyRandomList(self, head: 'Node') -> 'Node':
  3. # duplicate each node, insert behind
  4. p = head
  5. while p:
  6. nxt = p.next
  7. p.next = Node(p.val, nxt)
  8. p = nxt
  9. # random pointer
  10. p = head
  11. while p and p.next:
  12. curr = p.next
  13. nxt = curr.next
  14. curr.random = p.random.next if p.random else None
  15. p = nxt
  16. # next pointer
  17. p = head
  18. while p and p.next and p.next.next:
  19. curr = p.next
  20. nxt = curr.next
  21. curr.next = nxt.next
  22. p = nxt
  23. return head.next if head else None

题目分析

最简单的思路,用hash table存
如果不想用额外的空间,就需要充分利用原先链表的特性。
比如,新加入的节点先放到原节点的后边,更新完random之后,再更新next。

其它解法

naive的hash table解法

  1. class Solution:
  2. def copyRandomList(self, head: 'Node') -> 'Node':
  3. nodeMap = {}
  4. dummy = Node(0)
  5. p = head
  6. q = dummy
  7. while p:
  8. q.next = Node(p.val)
  9. nodeMap[p] = q.next
  10. p = p.next
  11. q = q.next
  12. p = head
  13. q = dummy.next
  14. while p:
  15. q.random = nodeMap[p.random] if p.random else None
  16. p = p.next
  17. q = q.next
  18. return dummy.next