138. Copy list with random pointer

Title:

Given a linked list, each node contains an additional random pointer that can point to any node or null node in the list.

It is required to return the Deep copy.  

 

Example:

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Interpretation:
The value of node 1 is 1, and its next and random pointers both point to node 2.
The value of node 2 is 2, its next pointer points to null, and the random pointer points to itself.

Train of thought:

1. Using hashmap, it is divided into two parts. Traverse the original linked list, do not do anything with random, and store the generated new nodes in hashmap. Traverse the original linked list again, only link its random part, and get the nodes of the new linked list from hashmap

2. Create a new list, link the new list to the back of the old one, a1b1a2b2a3b3 In the form of anbn, a is the old table and B is the new table. For the second time, traverse the new table from the beginning to access the random of the old table. The next random is the current node's random

Train of thought 1

    def copyRandomList(self, head: 'Node') -> 'Node':
        dic = {}
        if not head:
            return None
        p = head.next
        h = Node(head.val,None,None)
        q = h
        dic[head.val] = h
        while p:
            q.next = Node(p.val,None,None)
            q = q.next
            dic[p.val] = q
            p = p.next
        p = head
        q = h
        while p:
            if p.random:
                q.random = dic[p.random.val]
            q = q.next
            p = p.next
        return h

Train of thought 2

    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None
        p = head
        while p:    #Copy the new linked list node to the back of each old linked list node
            q = Node(p.val,p.next,None)
            p.next = q
            p = q.next
            
        p = head
        while p:  #Processing random
            if p.random:
                p.next.random = p.random.next
            p = p.next.next

        h = head.next
        q = h
        p = head
        while p: #Split two list s
            p.next = q.next
            p = p.next
            if not p:
                break
            q.next = p.next
            q = q.next

        return h

 

Posted on Mon, 02 Dec 2019 23:34:31 -0500 by Jason_London