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.
Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
一开始没太理解这道题的意思,又看了看deepcopy的意思https://blog.youkuaiyun.com/AIpush/article/details/102595709,
其实就是再复制一遍这个链表,关键在于这个random是随机链接一个ListNode的,怎么去找到这个ListNode。
这里就要用dict()的get操作了
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
dic = dict()
cur = head
while cur:
dic[cur] = Node(cur.val, None, None)
cur = cur.next
cur=head
while cur:
if cur.next:
dic[cur].next = dic.get(cur.next)
if cur.random:
dic[cur].random = dic.get(cur.random)
cur = cur.next
return dic.get(head)
或者使用python的collections.defaultdict()方法,参考https://blog.youkuaiyun.com/yangsong95/article/details/82319675
这样就可以只用一个循环解决
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
import collections as c
dic = c.defaultdict(lambda:Node(0,None,None))
dic[None]=None
p=head
while p:
dic[p].val = p.val
dic[p].next = dic[p.next]
dic[p].random = dic[p.random]
p=p.next
return dic[head]