其他分享
首页 > 其他分享> > leetcode138. Copy List with Random Pointer

leetcode138. Copy List with Random Pointer

作者:互联网

Construct a deep copy of the list. 

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

Your code will only be given the head of the original linked list.

Example 1:

Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

解法一:
建一个dict,先对每个点copy一个点存在dict的值里,再对每个dict的值,把next和random加上去。
注意:dic[i]如果没有值就会报错,所以这里用dic.get(i),防止有的点random是空,或者最后一个点next是空。
time: O(2n)
space: O(n)


"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        dic = {}
        node = cur = head
        while node:
            dic[node] = Node(node.val)
            node = node.next
        while cur:
            dic[cur].next = dic.get(cur.next)
            dic[cur].random = dic.get(cur.random)
            cur = cur.next
        return dic.get(head)
        

 

标签:node,Node,cur,random,dic,next,leetcode138,Copy,Pointer
来源: https://www.cnblogs.com/aegeanchan/p/15987854.html