my python solution with dictionary


  • 0
    A
    def copyRandomList(self, head):
        if head == None:
            return None
            
        current = head
        new_head = None
        previous = None
        hash_table = {}
        
        while current != None:
            new_node = RandomListNode(current.label)
            
            if current.random:
                new_node.random = current.random
                
            if previous != None:
                previous.next = new_node
            else:
                new_head = new_node
                
            hash_table[current] = new_node
            
            previous = new_node
            current = current.next
            
        new_current = new_head
        
        while new_current != None:
            if new_current.random != None:
                new_current_random = hash_table[new_current.random]
                
                new_current.random = new_current_random
            
            new_current = new_current.next
            
        return new_head
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.