题目链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer/
难度:中等

描述:
给你一个长度为n的链表,每个节点包含一个额外增加的随机指针random,该指针可以指向链表中的任何节点或空节点。

构造这个链表的深拷贝。深拷贝应该正好由n全新节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的next指针和random指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。

提示:
节点数:[0, 1000]

题解

迭代

遍历链表,复制每个节点(复制的节点的random = None),将复制的节点插入到原节点的后面:
138. 复制带随机指针的链表 - 图1

再次遍历,添加复制节点的random指针
138. 复制带随机指针的链表 - 图2
最后分离两个链表

  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. cur = head
  12. while cur is not None:
  13. new_node = Node(cur.val, cur.next, None)
  14. cur.next = new_node
  15. cur = cur.next.next
  16. cur = head
  17. while cur is not None:
  18. if cur.random is not None:
  19. cur.next.random = cur.random.next
  20. cur = cur.next.next
  21. dummy = Node(0, None, None)
  22. temp = dummy
  23. cur = head
  24. while cur is not None:
  25. temp.next = cur.next
  26. temp = temp.next
  27. cur.next = cur.next.next
  28. cur = cur.next
  29. return dummy.next

哈希表

建立一个哈希表,遍历链表,使key = original_nodevalue = new_node
再次遍历链表,给new_node加上nextrandom

  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. node_map = {}
  14. cur = head
  15. while cur is not None:
  16. new_node = Node(cur.val, None, None)
  17. node_map[cur] = new_node
  18. cur = cur.next
  19. cur = head
  20. while cur is not None:
  21. if cur.next is not None:
  22. node_map[cur].next = node_map[cur.next]
  23. if cur.random is not None:
  24. node_map[cur].random = node_map[cur.random]
  25. cur = cur.next
  26. return node_map[head]