All problems

Rotate List

Medium · linked list

You are given the head of a singly linked list and a non-negative integer k. Rotate the list to the right by k places and return the head of the rotated list.

One rotation to the right takes the last node and moves it to the front. Doing that k times produces the answer. The value of k can be larger than the length of the list.

An empty list stays empty. The nodes you receive are ListNode objects with a val and a next.

Examples

Example 1

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

Output: [4, 5, 1, 2, 3]

The last two nodes, 4 and 5, move to the front in the same order.

Example 2

Input: head = [7, 8, 9], k = 4

Output: [9, 7, 8]

Four rotations on three nodes is the same as one rotation.

Example 3

Input: head = [5, 6], k = 0

Output: [5, 6]

Constraints