复杂链表的复制
问题
请实现 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。
提示:
-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
💡本题的意思是复制一个链表并返回,这个链表与一般链表不同的是多了一个 random 指针
在这里,复制的意思是指 深拷贝(Deep Copy),类似我们常用的“复制粘贴”,事实上,与此对应的还有 浅拷贝,它们的区别是:
浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象还是共享同一块内存。但深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象。
💡图的基本单元是 顶点,顶点之间的关联关系称为 边,我们可以将此链表看成一个图
DFS 深度优先搜索
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
def dfs(head):
if not head: return None
if head in visited:
return visited[head]
# 创建新结点
copy = Node(head.val, None, None)
visited[head] = copy
copy.next = dfs(head.next)
copy.random = dfs(head.random)
return copy
visited = {}
return dfs(head)
BFS 广度优先搜索
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
visited = {}
def bfs(head):
# head为空的情况
if not head:
return head
que = collections.deque()
que.append(head)
copy = Node(head.val, None, None)
visited[head] = copy
while que:
temp = que.popleft()
if temp.next and temp.next not in visited:
visited[temp.next] = Node(temp.next.val, None, None)
que.append(temp.next)
if temp.random and temp.random not in visited:
visited[temp.random] = Node(temp.random.val, None, None)
que.append(temp.random)
visited[temp].next = visited.get(temp.next)
visited[temp].random = visited.get(temp.random)
return copy
return bfs(head)
二刷时-看了答案才会
hash字典
让 random 有所指
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return
ha = {}
headfin = headha = head
# 建立词典
while headha:
ha[headha] = Node(headha.val)
headha = headha.next
# 运用
while headfin:
ha[headfin].next = ha.get(headfin.next)
ha[headfin].random = ha.get(headfin.random)
headfin = headfin.next
return ha[head]