/92. Reverse Sublist in Singly Linked List

92. Reverse Sublist in Singly Linked List

Medium
Linked Lists51.1% acceptance

Given the head node of a singly linked list and two integer indices start_pos and end_pos (1-based, inclusive), reverse the nodes between positions start_pos and end_pos. Return the head node of the modified list.

Example 1

Input: head = ListNode(7, ListNode(8, ListNode(9, ListNode(10, ListNode(11))))) start_pos = 3 end_pos = 5

Output: [7, 8, 11, 10, 9]

Explanation: Nodes from position 3 to 5 are reversed.

Example 2

Input: head = ListNode(3) start_pos = 1 end_pos = 1

Output: [3]

Explanation: Single node list, no change.

Example 3

Input: head = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) start_pos = 1 end_pos = 4

Output: [4, 3, 2, 1]

Explanation: Entire list is reversed.

Constraints

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

Case 1

Input: head = ListNode(6, ListNode(7, ListNode(8, ListNode(9)))) start_pos = 2 end_pos = 3

Expected: [6, 8, 7, 9]

Case 2

Input: head = ListNode(4, ListNode(5, ListNode(6))) start_pos = 1 end_pos = 2

Expected: [5, 4, 6]

Case 3

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

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