• 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]
    
  • 相关阅读:
    MemCached总结二:数据管理指令
    MemCached总结一:Unbutu操作系统下memcached服务器安装和telnet方式连接memcache
    Laravel5 开启Debug
    状压dp
    树形dp
    区间dp
    线性dp
    背包九讲
    dp求解各种子串子序列
    线段树详解
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/10267332.html
Copyright © 2020-2023  润新知