题目链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
难度:中等

描述:
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null

题解

  1. """
  2. # Definition for a Node.
  3. class Node:
  4. def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
  5. self.val = int(x)
  6. self.next = next
  7. self.random = random
  8. """
  9. class Solution:
  10. def copyRandomList(self, head: 'Node') -> 'Node':
  11. if head is None:
  12. return None
  13. temp = head
  14. while temp is not None:
  15. new_node = Node(temp.val, temp.next)
  16. temp.next = new_node
  17. temp = new_node.next
  18. temp = head
  19. while temp is not None:
  20. if temp.random is not None:
  21. temp.next.random = temp.random.next
  22. temp = temp.next.next
  23. temp = head
  24. ret = head.next
  25. cur = ret
  26. while cur.next:
  27. temp.next = cur.next
  28. temp = temp.next
  29. cur.next = temp.next
  30. cur = cur.next
  31. temp.next = None
  32. return ret