-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopyList.py
33 lines (30 loc) · 930 Bytes
/
CopyList.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
# https://www.interviewbit.com/problems/copy-list/
# 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):
cur = head
while cur:
newNode = RandomListNode(cur.label)
newNode.next = cur.next
cur.next = newNode
cur = cur.next.next
cur = head
while cur:
tmp = cur.next.next
if tmp:
cur.next.next = tmp.next
else:
cur.next.next = None
if cur.random:
cur.next.random = cur.random.next
else:
cur.next.random = None
cur = tmp
return head.next