【leetcode】#雜湊表【Python】138. Copy List with Random Pointer 複製帶隨機指標的連結串列
阿新 • • 發佈:2018-12-21
連結:
題目:
給定一個連結串列,每個節點包含一個額外增加的隨機指標,該指標可以指向連結串列中的任何節點或空節點。要求返回這個連結串列的深度拷貝。
解法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]