FastPrepRotate a Linked List to the Right

Rotate a Linked List to the Right

NVIDIA logoNVIDIA● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

Given the head head of a singly linked list and a nonnegative integer k, move the final node to the front k times and return the new head.

A complete rotation preserves order. An empty list returns an empty list. The resulting list must terminate; it must not contain a cycle.

Function

rotateRight(head: ListNode, k: int) → ListNode

Examples

Example 1

head = [1,2,3,4,5]k = 2return = [4,5,1,2,3]

The final two nodes become the first two, without reversing them.

Example 2

head = [0,1,2]k = 4return = [2,0,1]

Four rightward rotations equal one rotation for a three-node list.

Example 3

head = []k = 7return = []

Rotating an empty list leaves it empty.

Constraints

  • The list contains 0 to 500 nodes.
  • -100 <= Node.val <= 100.
  • 0 <= k <= 2 * 10^9.

More NVIDIA problems

See NVIDIA hiring insights
public ListNode rotateRight(ListNode head, int k) {
    return head;
}
head[1,2,3,4,5]
k2
expected[4,5,1,2,3]
Checking account…