leetcode:复杂链表的复制
原题:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
我的解法
# 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 head==None:
return None
hd=head
thead=Node(hd.val)
t=thead
list2=[hd.random]
hd=hd.next
list=[thead]
while hd!=None:
n=Node(hd.val)
t.next=n
list2.append(hd.random)
list.append(n)
t=n
hd=hd.next
t1=thead
for i in range(len(list2)):
if list2[i]==None:
t1.random=None
t1=t1.next
continue
j=0
hd=head
while hd!=None:
if hd==list2[i]:
t1.random=list[j]
t1=t1.next
break
j+=1
hd=hd.next
return thead
官方解法
使用哈希和回溯法。
哈希 键:原链表结点 值:复制结点
回溯:让每个结点的拷贝相互独立
# 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 __init__(self):
self.hashNode={}
def copyRandomList(self, head):
if head==None:
return None
if head not in self.hashNode.keys():
headNew=Node(head.val)
self.hashNode[head]=headNew
headNew.next=self.copyRandomList(head.next)
headNew.random = self.copyRandomList(head.random)
return self.hashNode[head]

浙公网安备 33010602011771号