copy list with random pointer

解法1 利用hashtable

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
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class (object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None
dummy = head
m = {}
while head:
node = RandomListNode(head.label)
m[head] = node
head = head.next
head = dummy
while head:
if head.next:
m[head].next = m[head.next]
head = head.next
head = dummy
while head:
if head.random:
m[head].random = m[head.random]
head = head.next
return m[dummy]

解法2 inplace的做法, 并不能pass,complain pointer modified。不过我觉得解法没什么问题

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
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class (object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None
cur = head
while cur:
next = cur.next
node = RandomListNode(cur.label)
cur.next = node
node.next = next
cur = next
cur = head
while cur:
rand = cur.random
if rand:
cur.next.rand = rand.next
cur = cur.next.next
cur = head.next
while cur and cur.next:
cur.next = cur.next.next
cur = cur.next
return head