Problem description:

Given the head of a linked list, rotate the list to the right by k places.

Example 1:

1
2
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

Example 2:

1
2
Input: head = [0,1,2], k = 4
Output: [2,0,1]

Solution:

Identify that k might be greater than list size. We need to % to get how many rotation we should do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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 or k == 0:
return head
size = 0
dummy = ListNode(-1)
dummy.next, p = head, dummy
while p.next:
p, size = p.next, size+1
k %= size
step, mid = size - k, dummy
for _ in range(step):
mid = mid.next
p.next = dummy.next
dummy.next = mid.next
mid.next = None
return dummy.next

time complexity: $O(n)$
space complexity: $O(1)$
reference:
related problem: