Reverse a linked list II

problem [https://leetcode.com/problems/reverse-linked-list-ii/ 92. Reverse Linked List II].

Problem description
Reverse a linked list from position m to n. Do it in one-pass.


 * Note
 * 1 ≤ m ≤ n ≤ length of list.


 * Example
 * Input: 1 → 2 → 3 → 4 → 5 → NULL, m = 2, n = 4
 * Output: 1 → 4 → 3 → 2 → 5 → NULL

Analysis
The assumption in this problem is that 1 ≤ m ≤ n ≤ length of list, which means that m and n are always valid indices, and that we are reversing the linked list on the closed interval [m, n].

Also note that in this problem the head node has index 1, instead of 0 from the sense of arrays.

So we can do the following:
 * 1) Break the node into three segments: "1 through m-1", "m through n", "and n+1 through end".
 * 2) * If m = 1, then the first segment does not exist. Otherwise, we need to record the tail of the first segment.
 * 3) * If n = length of linked list, then the third segment does not exist. Otherwise, we need to record the head of the third segment.
 * 4) * Since we only do the problem in one-pass, we do not obtain the head of the third segment in advance. Instead, we will reach that head when we have finished reversing the second segment.
 * 5) Reverse the second segment.
 * 6) * The original tail of this segment has its  pointer pointing to the head of the third segment. The value will be   if the third segment does not exist. So we can record the head of the third segment.
 * 7) * After reversing the second segment, the original head of the second segment automatically becomes the tail, with its  pointer updated to be  . The original tail of this segment becomes the new head.
 * 8) * We need to record the new head of the second segment.
 * 9) Join the tail of the first segment (if it exists) with the new head of the second segment.
 * 10) * If the first segment does not exist, then we just return the new head of the second segment.
 * 11) Join the tail of the second segment (the original head of this segment) with the head of the third segment (if it exists).
 * 12) * If this segment does not exist, then the original head of the second segment will have its next pointer point to . In this case nothing is done for this step.

Complexity analysis

 * Time complexity
 * The time complexity is O(n), where n is the upper bound index of the interval to reverse.
 * This is because once we have finished reversing the segment, we just join the reversed segment with the head of the remaining nodes. We do not need to go further beyond the reversed segment.


 * Space complexity
 * Since we did not create additional data structures, the space complexity is O(1).