-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105.py
46 lines (40 loc) · 1.12 KB
/
105.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
"""
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:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
# write your code here
if not head:
return None
if not head.next:
return RandomListNode(head.label)
tmp = head
while tmp:
coptmp = RandomListNode(tmp.label)
coptmp.next = tmp.next
tmp.next = coptmp
tmp = coptmp.next
tmp = head
while tmp:
if tmp.random:
tmp.next.random = tmp.random.next
tmp = tmp.next.next
tmp = head
tmp2 = head.next
newHead = tmp.next
while tmp:
tmp.next = tmp2.next
if tmp.next:
tmp2.next = tmp.next.next
else:
break
tmp = tmp.next
tmp2 = tmp2.next
return newHead