/61. Rotate Linked List Right

61. Rotate Linked List Right

Medium
Linked Lists41.3% acceptance

Given the head node of a singly linked list and an integer shift_count, rotate the list to the right by shift_count positions. Return the new head node of the rotated list. The rotation should be performed in-place, and the list may be empty.

Example 1

Input: head = ListNode(7, ListNode(8, ListNode(9, ListNode(10)))) shift_count = 1

Output: [10,7,8,9]

Explanation: Rotating right by 1 moves the last node to the front.

Example 2

Input: head = ListNode(5, ListNode(6, ListNode(7))) shift_count = 3

Output: [5,6,7]

Explanation: Rotating by the list's length results in the same list.

Example 3

Input: head = None shift_count = 5

Output: []

Explanation: Empty list remains empty regardless of rotation.

Constraints

  • 0 <= number of nodes <= 500
  • -100 <= node value <= 100
  • 0 <= shift_count <= 2_000_000_000
Python (current runtime)

Case 1

Input: head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) shift_count = 3

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

Case 2

Input: head = ListNode(100, ListNode(200)) shift_count = 2

Expected: [100,200]

Case 3

Input: head = ListNode(42) shift_count = 100

Expected: [42]

Case 4

Input: head = ListNode(-1, ListNode(-2, ListNode(-3, ListNode(-4)))) shift_count = 5

Expected: [-4,-1,-2,-3]