Skip to content

Commit 199a7e4

Browse files
authored
Merge pull request #2138 from solairerove/main
Create: 61-Rotate-List.py
2 parents a33fd5d + 5a7a488 commit 199a7e4

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

python/0061-rotate-list.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
3+
if not head or not head.next or k == 0:
4+
return head
5+
6+
old_head = head
7+
8+
curr, size = head, 0
9+
while curr:
10+
curr, size = curr.next, size + 1
11+
12+
if k % size == 0:
13+
return head
14+
15+
k %= size
16+
slow = fast = head
17+
while fast and fast.next:
18+
if k <= 0:
19+
slow = slow.next
20+
fast = fast.next
21+
k -= 1
22+
23+
new_tail, new_head, old_tail = slow, slow.next, fast
24+
new_tail.next, old_tail.next = None, old_head
25+
26+
return new_head

0 commit comments

Comments
 (0)