Python algorithm diary list (list series) _leetcode 138. copy with random pointer

Given a list, each node contains a random additional pointer that can point to any node in the linked list node or empty.

The requirement to return a deep copy of the list. 

We use a linked list of n nodes to the input / output in a linked list. Each node with a [val, random_index] represents:

val: a Node.val integer representation.
random_index: random pointer node index (ranging from 0 to n-1); if you do not point to any node, was null.

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]]

Example 2:

输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:

输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]

示例 4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/copy-list-with-random-pointer

"""
# 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: 'Node') -> 'Node':
        if not head:
            return
        deep_dict = {}  #用字典存新旧节点
        old = head
        new = Node(0)
        while(head):  
            key = head
            new.next = Node(head.val) #新节点
            value = new.next
            new = new.next
            deep_dict.update({key:value}) #新旧节点存进字典
            head = head.next
        for key,value in deep_dict.items():
            if key.random:
            # 例value: a' ,key: a ,a.random = c,deep_dict[a.random]=c',所以a'.random = c'
                value.random = deep_dict[key.random]  
        return deep_dict[old]

 

 

Published 44 original articles · won praise 0 · Views 1901

Guess you like

Origin blog.csdn.net/weixin_39331401/article/details/104643955