Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Solution

# Definition for singly-linked list with a random pointer.
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
    # @param head: A RandomListNode
    # @return: A RandomListNode
    def copyRandomList(self, head):
        # write your code here
        dummy = RandomListNode(0) # made a misstake , dummy is a copy of dummy 
        tail = dummy
        dic = {}

        while head:
            node = RandomListNode(head.label)
            dic[head] = node
            tail.next = node
            tail = node
            head = head.next

        for node in dic:
            if node.random: # if could be a None so very important check point.
                dic[node].random = dic[node.random]

        return dummy.next #direclty return dummy.next

Last updated

Was this helpful?