forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-list-with-random-pointer.py
More file actions
34 lines (29 loc) · 1 KB
/
copy-list-with-random-pointer.py
File metadata and controls
34 lines (29 loc) · 1 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
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
if head==None: return head
curr = head
while curr:
temp = curr.next
new_node = RandomListNode(curr.label)
new_node.next = temp
curr.next = new_node
curr = curr.next.next
curr = head
while curr:
curr.next.random = curr.random.next if curr.random else None
curr = curr.next.next
curr = head
curr_copy = head.next
head_copy = head.next
while curr:
curr.next = curr.next.next
curr_copy.next = curr_copy.next.next if curr_copy.next else None
curr = curr.next
curr_copy = curr_copy.next
return head_copy