剑指 Offer 35. 复杂链表的复制

162 阅读1分钟

题目描述

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

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

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

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

解题思路: Map存储法

  1. 从head遍历整个链表, 将遍历到的node复制, 并且以 oldNode为key, newNode为value, 存入Map中
  2. 再次从head遍历链表, 从Map中取值进行新链表拼接, 其中
    • dic[oldNode] = 对应的newNode
    • dic[oldNode.next] = 对应的newNode.next
    • 注: 使用dic.get()方法是因为如果传入的是None, 会返回None, 用dic[]则会报错

示例代码

def copyRandomList(self, head: 'Node') -> 'Node':
    if not head: return None
    dic = {}
    cur = head
    while cur:
        dic[cur] = Node(cur.val)
        cur = cur.next
    cur = head
    while cur:
        dic[cur].next = dic.get(cur.next)
        dic[cur].random = dic.get(cur.random)
        cur = cur.next
    return dic[head]