-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0061_Rotate_List.py
More file actions
33 lines (27 loc) · 838 Bytes
/
Copy path0061_Rotate_List.py
File metadata and controls
33 lines (27 loc) · 838 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
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return None
# compute length
end = head
length = 1
while end.next:
length += 1
end = end.next
if k == length: # if k equals length -> no need to rotate -> return
return head
elif k > length: # if k > length -> take only the remainder
k %= length
end.next = head
idx = 0
while idx != length - k - 1:
idx += 1
head = head.next
new_head = head.next
head.next = None
return new_head