Leetcode[138] Copy List with Random Pointer

an error:keyerror,

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if head==None:
            return None
        
        cur=head.next
        ret=Node(head.val,None,None)
        pre=ret
        dic=dict()
        dic[ret]=head
        while cur!=None:
            node=Node(cur.val,None,None)
            pre.next=node
            dic[cur]=node
            pre=node
            cur=cur.next
            
        node=head
        cur=ret
        
        while cur:
            if node.random==None:
                cur.random=None
            else:
                cur.random=dic[node.random] #  
            cur=cur.next
            node=node.next
        return ret

Another method: insert a node in the middle of 2 node in original list

 """
# Definition for a Node.
class Node(object):
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        if head==None:
            return None
    
        #insert a new node in the middle
        cur=head
        while cur:
            node=Node(cur.val,None,None)
            tmp=cur.next
            cur.next=node
            node.next=tmp
            cur=cur.next.next
            
        #random pointer hanle
        cur=head
        while cur:
            if cur.random:
                cur.next.random=cur.random.next
            cur=cur.next.next
        
        #seperate the target deep copy list
        cur=head
        res=cur.next
        while cur:
            node=cur.next
            cur.next=cur.next.next
            
            if node.next:
                node.next=node.next.next
                
            cur=cur.next
            
            
        return res
        
            

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值