题目:
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
- val:一个表示 Node.val 的整数。
- random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
示例:
思路:
用一个字典visited
记录已经复制过的节点,键是原节点,值是拷贝节点。顺着next
指针遍历链表,如果节点存在于visited
,就拿出来直接用;否则新建一个节点,同时加入visited
。
代码:
"""
# Definition for a Node.
class Node:
def __init__(self, x, next=None, random=None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return head
visited = {}
res = head
while head:
if head not in visited:
visited[head] = Node(head.val)
headCopy = visited[head]
if head.next:
if head.next not in visited:
visited[head.next] = Node(head.next.val)
headCopy.next = visited[head.next]
if head.random:
if head.random not in visited:
visited[head.random] = Node(head.random.val)
headCopy.random = visited[head.random]
head = head.next
return visited[res]