forked from lilianweng/LeetcodePython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy_list_random_pointer.py
More file actions
69 lines (59 loc) · 1.63 KB
/
copy_list_random_pointer.py
File metadata and controls
69 lines (59 loc) · 1.63 KB
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
#!/usr/bin/env python
'''
Leetcode: Copy List with Random Pointer
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 __future__ import division
import random
import LinkedList
class Node(LinkedList.Node):
def __init__(self, value, next=None, prev=None, randp=None):
super(Node, self).__init__(value, next, prev)
self.randp = randp
def __str__(self):
if self.randp is None: s = '[%d]' % self.value
else: s = '[%d,%d]' % (self.value, self.randp.value)
if self.next:
s += '->(%s)' % str(self.next)
return s
# Brute-force
# create the list first and then set up the pointer
def copylist(head):
new_head = Node(head.value)
# Copy the list
prev_n = new_head
node = head.next
while node:
n = Node(node.value)
prev_n.next = n
prev_n = n
node = node.next
# Assign pointer
node = head
new_node = new_head
while node:
if node.randp:
# locate the pointer
h = head
newh = new_head
while h != node.randp:
h = h.next
newh = newh.next
new_node.randp = newh
node = node.next
new_node = new_node.next
print 'Orig:', head
print 'Copy:', new_head
if __name__ == '__main__':
n6 = Node(6)
n5 = Node(5, n6)
n4 = Node(4, n5)
n3 = Node(3, n4)
n2 = Node(2, n3)
n1 = Node(1, n2)
n1.randp = n4
n2.randp = n4
n4.randp = n6
n5.randp = n3
copylist(n1)