Python | Leetcode Python题解之第138题随机链表的复制
标题:https://img-blog.csdnimg.cn/direct/fd65c6414df7415cbd6fc0f0fd351f00.png
题解:
class Solution:
def copyRandomList(self, head: 'Optional') -> 'Optional':
allNode=[] # 用一个数组存储所有结点
cur1=head
while cur1:
allNode.append(cur1)
cur1=cur1.next
n=len(allNode)
allRandom=[-1]*n # 用一个数组存储所有节点的random指向的结点下标(下标-1表null)
for i in range(n):
randomNode=allNode.random
if not randomNode:
continue
for j in range(n):
if randomNode==allNode:
allRandom=j
break
dummy=Node(0)
cur2=dummy
for i in range(n):# 创建n个新节点存储在原allNode数组中
newnode=Node(allNode.val)
allNode=newnode
for i in range(n):# 将n个新节点串联起来
cur2.next=allNode
cur2=cur2.next
if allRandom!=-1:
cur2.random=allNode]
return dummy.next
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]