剑指 Offer 35. 复杂链表的复制 - 力扣(LeetCode) (leetcode-cn.com)

题目

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

示例 1:

2cmbvge1.bmp

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

示例 2:

2zrx4lgs.bmp

  1. 输入:head = [[1,1],[2,1]]
  2. 输出:[[1,1],[2,1]]

示例 3:

yp2kl3ne.bmp

  1. 输入:head = [[3,null],[3,0],[3,null]]
  2. 输出:[[3,null],[3,0],[3,null]]

示例 4:

  1. 输入:head = []
  2. 输出:[]
  3. 解释:给定的链表为空(空指针),因此返回 null

提示:

  • -10000 <= Node.val <= 10000
  • Node.random为空(null)或指向链表中的节点。
  • 节点数目不超过 1000 。
    注意:本题与主站 138 题相同:https://leetcode-cn.com/problems/copy-list-with-random-pointer/

    初始代码

    ```python “””

    Definition for a Node.

    class Node: def init(self, x: int, next: ‘Node’ = None, random: ‘Node’ = None):
    1. self.val = int(x)
    2. self.next = next
    3. self.random = random
    “”” class Solution: def copyRandomList(self, head: ‘Node’) -> ‘Node’:
  1. <a name="Dh22x"></a>
  2. ### 提交代码
  3. ```python
  4. """
  5. # Definition for a Node.
  6. class Node:
  7. def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
  8. self.val = int(x)
  9. self.next = next
  10. self.random = random
  11. """
  12. class Solution:
  13. def copyRandomList(self, head: 'Node') -> 'Node':
  14. if not head: return
  15. cur = head
  16. # 1. 复制各节点,并构建拼接链表
  17. while cur:
  18. tmp = Node(cur.val)
  19. tmp.next = cur.next
  20. cur.next = tmp
  21. cur = tmp.next
  22. # 2. 构建各新节点的 random 指向
  23. cur = head
  24. while cur:
  25. if cur.random:
  26. cur.next.random = cur.random.next
  27. cur = cur.next.next
  28. # 3. 拆分两链表
  29. cur = res = head.next
  30. pre = head
  31. while cur.next:
  32. pre.next = pre.next.next
  33. cur.next = cur.next.next
  34. pre = pre.next
  35. cur = cur.next
  36. pre.next = None # 单独处理原链表尾节点
  37. return res # 返回新链表头节点

分析

剑指 Offer 35. 复杂链表的复制(哈希表 / 拼接与拆分,清晰图解) - 复杂链表的复制 - 力扣(LeetCode)z0wj3x18.bmp