题目:
题解:
class Solution:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':allNode=[] # 用一个数组存储所有结点cur1=headwhile cur1:allNode.append(cur1)cur1=cur1.nextn=len(allNode)allRandom=[-1]*n # 用一个数组存储所有节点的random指向的结点下标(下标-1表null)for i in range(n):randomNode=allNode[i].randomif not randomNode:continuefor j in range(n):if randomNode==allNode[j]:allRandom[i]=jbreakdummy=Node(0)cur2=dummyfor i in range(n):# 创建n个新节点存储在原allNode数组中newnode=Node(allNode[i].val)allNode[i]=newnodefor i in range(n):# 将n个新节点串联起来cur2.next=allNode[i]cur2=cur2.nextif allRandom[i]!=-1:cur2.random=allNode[allRandom[i]]return dummy.next