链接:
https://leetcode-cn.com/problems/copy-list-with-random-pointer/
题目:
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的深度拷贝。
解法1:先循环一遍,把node建完,把所有的node存在dic的key里;之后再循环一遍,把关系整好
class Solution:
def copyRandomList(self, head):
dic = dict()
m = n = head
while m:
dic[m] = RandomListNode(m.label)
m = m.next
while n:
dic[n].next = dic.get(n.next)
dic[n].random = dic.get(n.random)
n = n.next
return dic.get(head)
解法2:
def copyRandomList(self, head):
dic = collections.defaultdict(lambda: RandomListNode(0))
dic[None] = None
n = head
while n:
dic[n].label = n.label
dic[n].next = dic[n.next]
dic[n].random = dic[n.random]
n = n.next
return dic[head]
本文探讨了如何解决LeetCode上的一道难题——深度拷贝一个带有额外随机指针的链表。提供了两种解决方案,一种是通过两次遍历,首先创建所有节点,然后建立节点间的关系;另一种是使用defaultdict简化代码,一次遍历完成节点创建和关系建立。

2100

被折叠的 条评论
为什么被折叠?



