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]

转载于:https://www.cnblogs.com/bernieloveslife/p/10267332.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值