Rotate List

Given the head of a linked list and an integer k, rotate the list to the right by k places (i.e., move last k nodes to the front). Example: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] Explanation: Rotating by 2 moves the last two nodes [4,5] to front. Pattern focus: Two-Pointer Gap (find list length and reconnect).

Input Format

head = ListNode, k = int

Output Format

return ListNode

Constraints

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

Examples

Example 1:

Input:

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

Output:

[4,5,1,2,3]

Explanation:

Last 2 nodes [4,5] moved to front.

Example 2:

Input:

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

Output:

[2,0,1]

Explanation:

k wraps around (effective 4 mod 3 = 1).

Loading...
Rotate List - Linked List DSA Problem