File tree 1 file changed +48
-0
lines changed
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ 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.
3
+
4
+ Return a deep copy of the list.
5
+
6
+
7
+ '''
8
+
9
+ # Definition for singly-linked list with a random pointer.
10
+ # class RandomListNode(object):
11
+ # def __init__(self, x):
12
+ # self.label = x
13
+ # self.next = None
14
+ # self.random = None
15
+
16
+ class Solution (object ):
17
+ def copyRandomList (self , head ):
18
+ """
19
+ :type head: RandomListNode
20
+ :rtype: RandomListNode
21
+ """
22
+ if not head :
23
+ return None
24
+
25
+ dic = {}
26
+ cur = head
27
+ while cur :
28
+ if cur not in dic :
29
+ mirror = RandomListNode (cur .label )
30
+ dic [cur ] = mirror
31
+
32
+ if cur .next :
33
+ if cur .next not in dic :
34
+ mirror = RandomListNode (cur .next .label )
35
+ dic [cur .next ] = mirror
36
+
37
+ dic [cur ].next = dic [cur .next ]
38
+
39
+ if cur .random :
40
+ if cur .random not in dic :
41
+ mirror = RandomListNode (cur .random .label )
42
+ dic [cur .random ] = mirror
43
+
44
+ dic [cur ].random = dic [cur .random ]
45
+
46
+ cur = cur .next
47
+
48
+ return dic [head ]
You can’t perform that action at this time.
0 commit comments