-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
31 lines (27 loc) · 806 Bytes
/
solution.py
File metadata and controls
31 lines (27 loc) · 806 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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
"""
dummy = RandomListNode(-1)
d = dummy
node_map = {}
p = head
while p:
d.next = RandomListNode(p.label)
node_map[p] = d.next
p = p.next
d = d.next
d = dummy.next
while head:
d.random = node_map[head.random] if head.random else None
d = d.next
head = head.next
return dummy.next