Search⌘ K
AI Features

Solution: Rotate List

Explore how to rotate a singly linked list to the right by a given number of positions using an efficient in-place method. This lesson helps you understand traversing linked lists, computing length, handling rotations with modulus to eliminate full cycles, and breaking circular links to form the rotated list. You will learn an optimal solution that runs in linear time and uses constant extra space.

Statement

You are given the head of a singly linked list and a non-negative integer k. Your task is to rotate the list to the right by k positions.

A right rotation by 1 means the last node becomes the new head, and every other node shifts one position to the right.

Return the head of the rotated linked list.

Constraints:

  • The number of nodes in the list is in the range [0, ...