FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/linkedlist/copy_random_pointer.py at master · Mu-L/algorithms-python · GitHub
Mu-L
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
linkedlist
/
copy_random_pointer.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (41 loc) · 1.07 KB
Breadcrumbs
algorithms-python
/
algorithms
/
linkedlist
/
copy_random_pointer.py
Copy path
File metadata and controls
48 lines (41 loc) · 1.07 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
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.
"""
from
collections
import
defaultdict
class
RandomListNode
(
object
):
def
__init__
(
self
,
label
):
self
.
label
=
label
self
.
next
=
None
self
.
random
=
None
def
copy_random_pointer_v1
(
head
):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
dic
=
dict
()
m
=
n
=
head
while
m
:
dic
[
m
]
=
RandomListNode
(
m
.
label
)
m
=
m
.
next
while
n
:
dic
[
n
].
next
=
dic
.
get
(
n
.
next
)
dic
[
n
].
random
=
dic
.
get
(
n
.
random
)
n
=
n
.
next
return
dic
.
get
(
head
)
# O(n)
def
copy_random_pointer_v2
(
head
):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
copy
=
defaultdict
(
lambda
:
RandomListNode
(
0
))
copy
[
None
]
=
None
node
=
head
while
node
:
copy
[
node
].
label
=
node
.
label
copy
[
node
].
next
=
copy
[
node
.
next
]
copy
[
node
].
random
=
copy
[
node
.
random
]
node
=
node
.
next
return
copy
[
head
]
Back
|
FazBrowse Home
|
New Git URL