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

    示例 1:
    输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
    输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

    示例 2:
    输入:head = [[1,1],[2,1]]
    输出:[[1,1],[2,1]]

    示例 3:
    输入:head = [[3,null],[3,0],[3,null]]
    输出:[[3,null],[3,0],[3,null]]

    示例 4:
    输入:head = []
    输出:[]
    解释:给定的链表为空(空指针),因此返回 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: 'Optional[Node]') -> 'Optional[Node]':
    11. # if head is None:
    12. # return None
    13. # cur = head
    14. # next = None
    15. # while cur is not None: # 1 -> 2 变化成 1 -> 1' -> 2 -> 2'
    16. # next = cur.next
    17. # cur.next = Node(cur.val)
    18. # cur.next.next = next
    19. # cur = next
    20. # cur = head
    21. # curcopy = None
    22. # while cur is not None: # 一对一对取出来连random指针
    23. # next = cur.next.next
    24. # curcopy = cur.next
    25. # curcopy.random = cur.random.next if cur.random is not None else None
    26. # cur = next
    27. # res = head.next
    28. # cur = head
    29. # while cur is not None: # 分离链表
    30. # next = cur.next.next
    31. # curcopy = cur.next
    32. # cur.next = next
    33. # curcopy.next = next.next if next is not None else None
    34. # cur = next
    35. # return res
    36. hashmap = dict()
    37. cur = head
    38. while cur is not None:
    39. hashmap[cur] = Node(cur.val)
    40. cur = cur.next
    41. cur = head
    42. while cur is not None:
    43. hashmap.get(cur).next = hashmap.get(cur.next)
    44. hashmap.get(cur).random = hashmap.get(cur.random)
    45. cur = cur.next
    46. return hashmap.get(head)
    1. class Solution:
    2. def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
    3. if head is None:
    4. return None
    5. cur = head
    6. next = None
    7. while cur is not None: # 1 -> 2 变化成 1 -> 1' -> 2 -> 2'
    8. next = cur.next
    9. cur.next = Node(cur.val)
    10. cur.next.next = next
    11. cur = next
    12. cur = head
    13. curcopy = None
    14. while cur is not None: # 一对一对取出来连random指针
    15. next = cur.next.next
    16. curcopy = cur.next
    17. curcopy.random = cur.random.next if cur.random is not None else None
    18. cur = next
    19. res = head.next
    20. cur = head
    21. while cur is not None: # 分离链表
    22. next = cur.next.next
    23. curcopy = cur.next
    24. cur.next = next
    25. curcopy.next = next.next if next is not None else None
    26. cur = next
    27. return res