Copy List with Random Pointer
Description:
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.
Challenge
Could you solve it with O(1) space?
Code:
"""
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
dic = {}
tmp = RandomListNode(0)
pointer, newHead = head, tmp
while pointer:
newNode = RandomListNode(pointer.label)
newHead.next = dic[pointer] = newNode
pointer, newHead = pointer.next, newHead.next
pointer, newHead = head, tmp
while pointer:
if pointer.random:
newHead.next.random = dic[pointer.random]
pointer, newHead = pointer.next, newHead.next
return tmp.next