class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
dic = {}
prior = Node(0)
temp_1 = prior
temp_2 = head
while head:
node = Node(head.val)
dic[head] = node
prior.next = node
prior = node
head = head.next
prior.next = None
temp_1 = temp_1.next
res = temp_1
head = temp_2
while head:
if not head.random:
dic[head].random = None
else:
dic[head].random = dic[head.random]
head = head.next
return temp_1
方法二:
深度遍历
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 = {}
方法三:
先处理next,后处理random
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
dic = {}
prior = Node(0)
temp_1 = prior
temp_2 = head
while head:
node = Node(head.val)
dic[head] = node
prior.next = node
prior = node
head = head.next
prior.next = None
temp_1 = temp_1.next
res = temp_1
head = temp_2
while head:
if not head.random:
dic[head].random = None
else:
dic[head].random = dic[head.random]
head = head.next
return temp_1
方法四:
结点后复制结点,再分裂链表
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
ori = head
while head:
temp = head.next
node = Node(head.val)
head.next = node
node.next = temp
head =temp
temp1 = ori
temp2 = ori.next
while temp1:
if temp1.random:
temp2.random = temp1.random.next
else:
temp2.random = None
temp1 = temp2.next
if temp2.next:
temp2 = temp1.next
else:
break
temp1 = ori
temp2 = ori.next
res = temp2
while temp1:
temp1.next = temp2.next
temp1 = temp2.next
if temp2.next:
temp2.next = temp1.next
temp2 = temp1.next
else:
temp2.next = None
return res
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof