forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopy List with Random Pointer.py
91 lines (69 loc) · 1.96 KB
/
Copy List with Random Pointer.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from collections import defaultdict
"""
# 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]':
# ll=res
# k=0
# ind=0
# kmk=1
jj=None
g=defaultdict(lambda:-1)
k=0
hh=head
while(head):
res=Node(head.val)
if k==0:
jj=res
if k==1:
prev.next=res
g[head]=res
prev=res
k=1
head=head.next
# print(g)
# for i in g:
# print(i.val,g[i].val)
kk=jj
mm=jj
# print(head)
while(hh):
if hh.random!=None:
jj.random=g[hh.random]
else:
jj.random=None
hh=hh.next
jj=jj.next
# head=head.next
kkk=kk
# while(kk):
# print(kk.val)
# kk=kk.next
return kkk
# if g[ind]!=-1:
# g[ind].random=res
# res=Node(head.val)
# if kmk==1:
# ll=res
# kmk=0
# mm=head.next
# if mm:
# jk=Node(mm.val)
# res.next=jk
# if head.random !=None:
# g[head.random]=res
# else:
# res.random=None
# head=head.next
# ind+=1
# # res=res.next
# return ll
# if k==0:
# res.val=head.val
# mm=head.next