-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path138 Copy List with Random Pointer.py
73 lines (54 loc) · 1.65 KB
/
138 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
"""
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.
Author: Rajeev Ranjan
"""
# Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
def copyRandomList(self, head):
"""
Algorithm:
Duplicate the node in the list
Split the list into two
A->B->C
A->A'->B->B'->C->C'
A->B->C
A'->B'->C'
:param head: RandomListNode
:return: RandomListNode
"""
# duplicate
dummy = RandomListNode(0)
dummy.next = head
pre = dummy
while pre.next:
cur = pre.next
cur_copy = RandomListNode(cur.label)
temp = cur.next
cur.next = cur_copy
cur_copy.next = temp
pre = pre.next.next
# copy random
pre = dummy
while pre.next:
cur = pre.next
if cur.random:
cur.next.random = cur.random.next # for duplicated node. NEXT IS RANDOM
pre = pre.next.next
# split
pre = dummy
head_copy = pre.next.next if pre.next else None
while pre.next:
cur = pre.next
cur_copy = cur.next
cur.next = cur_copy.next
if cur_copy.next:
cur_copy.next = cur_copy.next.next
pre = pre.next
return head_copy