Python One Pass Solution


  • 0
    W
    class Solution(object):
        def copyRandomList(self, head):
            if head is None:
                return None
            
            copyHead = RandomListNode(head.label)    
            m = head
            n = copyHead
            dict = {m: n}
            
            while m:
                if m.next:
                    if m.next not in dict:
                        dict[m.next] = RandomListNode(m.next.label)
                    n.next = dict[m.next]
                        
                if m.random:
                    if m.random not in dict:
                        dict[m.random] = RandomListNode(m.random.label)
                    n.random = dict[m.random]
                
                m = m.next
                n = n.next
                
            return copyHead
    

Log in to reply
 

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