Skip to content

Latest commit

 

History

History
76 lines (53 loc) · 1.64 KB

_138. Copy List with Random Pointer.md

File metadata and controls

76 lines (53 loc) · 1.64 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 27, 2024

Last updated : June 27, 2024


Related Topics : Hash Table, Linked List

Acceptance Rate : 57.98 %


Solutions

Python

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        if not head :
            return None

        origNodes = {}
        newNodes  = []

        newHead = Node(head.val)

        origCurr = head
        curr = newHead

        indx = 0
        origNodes[origCurr] = indx
        newNodes.append(curr)


        while origCurr.next :
            indx += 1
            origCurr = origCurr.next
            origNodes[origCurr] = indx
            curr.next = Node(origCurr.val)
            curr = curr.next
            newNodes.append(curr)
        
        curr = newHead
        origCurr = head

        while origCurr :
            if origCurr.random :
                curr.random = newNodes[origNodes.get(origCurr.random)]
            
            origCurr = origCurr.next
            curr = curr.next
        
        return newHead