/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 linked list to the right by shift_count positions. Return the new head node of the rotated list.

Example 1

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

Output: ListNode(10, ListNode(7, ListNode(8, ListNode(9))))

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

Example 2

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

Output: ListNode(3, ListNode(4, ListNode(5)))

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

Example 3

Input: head = None shift_count = 5

Output: None

Explanation: Empty list remains unchanged.

Constraints

  • 0 <= number of nodes in the linked list <= 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, ListNode(6)))))) shift_count = 3

Expected: ListNode(4, ListNode(5, ListNode(6, ListNode(1, ListNode(2, ListNode(3))))))

Case 2

Input: head = ListNode(11, ListNode(22, ListNode(33))) shift_count = 0

Expected: ListNode(11, ListNode(22, ListNode(33)))

Case 3

Input: head = ListNode(100) shift_count = 10

Expected: ListNode(100)

Case 4

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

Expected: ListNode(-3, ListNode(-4, ListNode(-1, ListNode(-2))))