mediumLinked List 0 views

Rotate a Linked List

Rotate a singly-linked list to the right by k places, wrapping around as needed.

Given the head of a singly-linked list, rotate the list to the right by k places, where k is a non-negative integer.

Rotating to the right by one place moves the last node of the list to the front, shifting every other node one position to the right.

k may be larger than the number of nodes in the list, in which case the rotation wraps around accordingly (rotating by the list's length has no effect at all).

Return the values of the rotated list.

Example 1

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

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

Example 2

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

Output: [2,0,1]

Explanation: Rotating a 3-node list by 4 places has the same effect as rotating it by 4 mod 3 = 1 place.

Example 3

Input: head = [], k = 3

Output: []

Explanation: Rotating an empty list leaves it empty.

Constraints

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

Follow-up

Can you compute the new head and new tail using a single pass that both measures the list's length and locates the rotation point, rather than two separate full traversals?

Hints

Companies

No companies reported yet.

Discussion

Sign in to join the discussion.

Loading discussion...

Test results

No test cases yet.