Python Solution O(n) time and O(1) space.


  • 0
    V
    class Solution(object):
        def copyRandomList(self, head):
            """
            :type head: RandomListNode
            :rtype: RandomListNode
            """
            temp = RandomListNode(0)
            t1 = temp
            while(head):
                newNode = RandomListNode(head.label)
                newNode.next = head.next
                if head.random:
                    newNodeRandom = RandomListNode(head.random.label)
                    newNodeRandom.next = head.random.next
                    newNodeRandom.random = head.random.random
                else:
                    newNodeRandom = None
                
                newNode.random = newNodeRandom
                temp.next = newNode
                temp = temp.next
                head = head.next
                
            return t1.next
    

Log in to reply
 

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