Techie Delight
Coding made easy
Write an efficient algorithm to reverse the specified portion of a given linked list.


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

The problem can be easily solved iteratively by dividing the solution into three parts. To reverse a list from position m to n, you need to:

This can be effectively implemented as 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

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

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

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 above solution is O(n) and no extra space is used by the solution.

Exercise: Write recursive version of above solution.
source