-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrotate-list.py
More file actions
36 lines (28 loc) · 923 Bytes
/
rotate-list.py
File metadata and controls
36 lines (28 loc) · 923 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
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
if not head: return head
def list_length(node):
dummy_head = ListNode(0, node)
res = 0
while dummy_head.next:
res += 1
dummy_head = dummy_head.next
return res
length = list_length(head)
k = k % length
if k == 0: return head
curr = ListNode(0, head)
for _ in range(k):
curr = curr.next
end = curr
curr = ListNode(0, head)
while end.next:
end, curr = end.next, curr.next
end.next = head
new_head = curr.next
curr.next = None
return new_head