链接:
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]