-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy_linked_list_random_pointer.py
63 lines (52 loc) · 1.5 KB
/
copy_linked_list_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
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
class Solution(object):
def print_list(self, head):
current = head
print "[",
while current != None:
print current.val,
current = current.next
if not current is None:
print ",",
print "]",
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
curr = head
while curr:
new_node = Node(curr.val, None, None)
tmp = curr.next
curr.next = new_node
new_node.next = tmp
curr = tmp
prev = head
while prev:
curr = prev.next
if prev.random:
curr.random = prev.random.next
prev = curr.next
org_head = head
new_head = head.next
final_head = new_head
while org_head and org_head.next and new_head and new_head.next:
org_head.next = org_head.next.next
new_head.next = new_head.next.next
org_head = org_head.next
new_head = new_head.next
org_head.next = None
new_head.next = None
return final_head
node = Node(1, None, None)
node_2 = Node(2, None, None)
node.next = node_2
node.random = node_2
node_2.random = node_2
abc = Solution()
abc.copyRandomList(node)