-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListwithRandomPointer.py
More file actions
40 lines (34 loc) · 1021 Bytes
/
CopyListwithRandomPointer.py
File metadata and controls
40 lines (34 loc) · 1021 Bytes
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
# 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):
if head == None:
return None
p = head
while p:
newNode = RandomListNode(p.label)
newNode.next = p.next
p.next = newNode
p = p.next.next
p = head
while p:
if p.random:
p.next.random = p.random.next
p = p.next.next
newhead = head.next
pold = head
pnew = newhead
while pnew.next:
pold.next = pnew.next
pold = pold.next
pnew.next = pold.next
pnew = pnew.next
pnew.next = None
pold.next = None
return newhead