Accepted python solution with Hash


  • 0
    L
    class Solution:
        # @param head, a RandomListNode
        # @return a RandomListNode
        def copyRandomList(self, head):
            if head == None:
                return None
            mapping = {}
           
            newHead = RandomListNode(head.label)
            mapping[head] = newHead
            curr2 = newHead
            curr1 = head
            # copy the basic linked list without random pointers
            while curr1.next != None:
                curr1 = curr1.next
                curr2.next = RandomListNode(curr1.label)
                curr2 = curr2.next
                if not mapping.has_key(curr1):
                    mapping[curr1] = curr2
            
            curr2 = newHead
            curr1 = head
            
            # copy the random pointers
            while curr1:
                if curr1.random == None:
                    curr1 = curr1.next
                    curr2 = curr2.next
                else:
                    curr2.random = mapping[curr1.random]
                    curr1 = curr1.next
                    curr2 = curr2.next
            return newHead

Log in to reply
 

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