138. Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
分析:
题目要求是返回原list的一个deep copy,若不存在random指针,只需要遍历一遍list,将节点不断添加到新的链表中即可。
而对于本题,首先遍历一遍list,用dic保存所有节点所对应的新节点(仅做初始化,不对next random指针操作)
之后遍历一遍节点,根据dic中保存的结果修改指针。
dic.get在找不到的时候返回none,而dic[]在找不到直接error。
# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return head
dic = {}
temp,w = head,head
while temp:
dic[temp] = RandomListNode(temp.label)
temp = temp.next
while w:
dic[w].next = dic.get(w.next) #而不是dic[w].next = w.next,dic.get(w.next)是新的list中的节点,而w.next是原list中的节点
dic[w].random = dic.get(w.random)
w = w.next
return dic[head]