/92. Reverse Linked List II

92. Reverse Linked List II

Medium
Linked Lists51.1% acceptance

Given the head node of a singly linked list and two integer indices start_index and end_index (1-based, inclusive), reverse the nodes of the list from position start_index to position end_index. Return the head node of the modified linked list.

Example 1

Input: head = ListNode(10, ListNode(20, ListNode(30, ListNode(40, ListNode(50))))) start_index = 2 end_index = 5

Output: [10,50,40,30,20]

Explanation: Nodes from position 2 to 5 are reversed.

Example 2

Input: head = ListNode(7) start_index = 1 end_index = 1

Output: [7]

Explanation: Single node list, no change.

Example 3

Input: head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) start_index = 1 end_index = 3

Output: [3,2,1,4]

Explanation: Nodes from position 1 to 3 are reversed.

Constraints

  • 1 <= number of nodes <= 500
  • -500 <= node value <= 500
  • 1 <= start_index <= end_index <= number of nodes
Python (current runtime)

Case 1

Input: head = ListNode(8, ListNode(9, ListNode(10, ListNode(11, ListNode(12))))) start_index = 3 end_index = 4

Expected: [8,9,11,10,12]

Case 2

Input: head = ListNode(100, ListNode(200, ListNode(300))) start_index = 1 end_index = 2

Expected: [200,100,300]

Case 3

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

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