class
Node:
def
__init__(
self
, data):
self
.data
=
data
self
.
next
=
None
self
.random
=
None
class
MyDictionary(
dict
):
def
__init__(
self
):
super
().__init__()
self
=
dict
()
def
add(
self
, key, value):
self
[key]
=
value
class
LinkedList:
def
__init__(
self
, node):
self
.head
=
node
def
__repr__(
self
):
temp
=
self
.head
while
temp
is
not
None
:
random
=
temp.random
random_data
=
(random.data
if
random
is
not
None
else
-
1
)
data
=
temp.data
print
(f"Data
-
{data},
Random data: {random_data}")
temp
=
temp.
next
return
""
def
push(
self
, data):
node
=
Node(data)
node.
next
=
self
.head
self
.head
=
node
def
clone(
self
):
original
=
self
.head
clone
=
None
mp
=
MyDictionary()
while
original
is
not
None
:
clone
=
Node(original.data)
mp.add(original, clone)
original
=
original.
next
original
=
self
.head
while
original
is
not
None
:
clone
=
mp.get(original)
clone.
next
=
mp.get(original.
next
)
clone.random
=
mp.get(original.random)
original
=
original.
next
return
LinkedList(
self
.head)
l
=
LinkedList(Node(
5
))
l.push(
4
)
l.push(
3
)
l.push(
2
)
l.push(
1
)
l.head.random
=
l.head.
next
.
next
l.head.
next
.random
=
l.head.
next
.
next
.
next
l.head.
next
.
next
.random
=
l.head.
next
.
next
.
next
.
next
l.head.
next
.
next
.
next
.random
=
(l.head.
next
.
next
.
next
.
next
.
next
)
l.head.
next
.
next
.
next
.
next
.random
=
l.head.
next
clone
=
l.clone()
print
(
"Original linked list"
)
print
(l)
print
(
"Cloned linked list"
)
print
(clone)