Problem 205180 · medium · Level 02 Linear Data Structures

Reverse a Middle Segment

linked list · reversal · pointer manipulation

Given the head of a singly linked list and two 1-based positions left and right with left <= right, reverse the nodes from position left to position right inclusive and return the head.

Examples

Input:  head = 7 -> 3 -> 9 -> 4 -> 6 -> 1, left = 2, right = 5
Output: 7 -> 6 -> 4 -> 9 -> 3 -> 1

Input:  head = 8, left = 1, right = 1
Output: 8

Constraints

  • right <= number of nodes
  • Target: O(n) time, O(1) extra space, one pass

Goals

  • Reverse a sub-range of nodes in place
  • Reconnect both ends of the reversed segment correctly
Starting Python…