Write an efficient algorithm to reverse the specified portion of a given linked list.

For example,

Input:
 
Linked List: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> None
 
start position = 2
end position = 5
 
Output: 1 —> 5 —> 4 —> 3 —> 2 —> 6 —> 7 —> None

Practice this problem

We can easily solve the problem iteratively by dividing the solution into three parts. To reverse a list from position m to n, do the following:

  1. Skip the first m nodes.
  2. Reverse the sublist from position m to n using the same previous-current-next strategy used in the solution to reverse a complete linked list.
  3. Rearrange the pointers and return the head node.

This can be effectively implemented as the following in C++, Java, and Python:

C++


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> null
Reversed linked list: 1 —> 5 —> 4 —> 3 —> 2 —> 6 —> 7 —> null

Java


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> null
Reversed linked list: 1 —> 5 —> 4 —> 3 —> 2 —> 6 —> 7 —> null

Python


Download  Run Code

Output:

Original linked list: 1 —> 2 —> 3 —> 4 —> 5 —> 6 —> 7 —> None
Reversed linked list: 1 —> 5 —> 4 —> 3 —> 2 —> 6 —> 7 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

 
Exercise: Write recursive version of above solution.