zoukankan      html  css  js  c++  java
  • 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]
    
  • 相关阅读:
    @Controller 与 @RestController 的区别
    Java泛型
    Java面试被经常问到的常用算法
    jdk和jre的区别
    Spring获取对象的方式
    xsi:schemaLocation的作用
    SpringBoot学习(一)
    docker-elk装IK自定义分词库
    MySQL存储引擎
    docker环境下elasticsearch安装ik和拼音分词
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/10267332.html
Copyright © 2011-2022 走看看