138. Copy List with Random Pointer
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if head is None:
return head
dummy = RandomListNode(-1)
cur = dummy
curOld = head
mapping = {}
mapping[None] = None
while(curOld):
cur.next = RandomListNode(curOld.label)
mapping[curOld] = cur.next
cur = cur.next
curOld = curOld.next
cur = dummy
curOld = head
while(curOld):
cur.next.random = mapping[curOld.random] # when random is None, traversing linked list won't add none in the dictionary, we need to do it manually
cur = cur.next
curOld = curOld.next
return dummy.next
'''Last updated