Reverse Linked List II

Practice this coding question on Coding Gurukul.

Problem statement

Given a singly linked list and positions left and right, reverse only the nodes from left through right, including both endpoints. Positions are one-based. Keep all nodes before left and after right in their original order. Print the resulting values. If left equals right, the list does not change. Implement the reversal by changing next links, using O(n) time and O(1) extra space. Worked example For [1, 2, 3, 4, 5], reversing positions 2 through 4 gives [1, 4, 3, 2, 5].

Input format

First line: n left right. Second line: n integer node values in list order.

Output format

Print the resulting n values separated by spaces.

Constraints

1 <= n <= 100000; 1 <= left <= right <= n; -10^9 <= value <= 10^9.

Sample input

5 2 4
1 2 3 4 5

Sample output

1 4 3 2 5

Sign in to run or submit a solution in C++, Java or Python.