4

Reverse A LL

Difficulty: MEDIUM
Contributed By
Avg. time to solve
30 min
Success Rate
65%

Problem Statement

Ninjas is practicing problems on the linked list. He came across a problem in which he has given a linked list of ‘N’ nodes and two integers, ‘LOW’ and ‘HIGH’. He has to return the linked list ‘HEAD’ after reversing the nodes between ‘LOW’ and ‘HIGH’, including the nodes at positions ‘LOW’ and ‘HIGH’.

Input Format :
The first line of input contains an integer ‘T’, the number of test cases.

The first line of each test case contains the linked list separated by space and terminated by -1.

The second line of each test case contains two space-separated integers, representing the ‘LOW’ and ‘HIGH’ integers, respectively.
Output Format :
For each test case, print the updated linked list.

Output for each test case will be printed in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 3*10^3
1 <= LOW <= RIGHT <= N

Time Limit: 1 sec
Follow Up: Can you solve it using constant space i.e O(1) space complexity?
Sample Input 1 :
2
1 3 2 4 6 5 -1
2 3
1 3 7 4 -1
2 4
Sample Output 1 :
1 2 3 4 6 5
1 4 7 3
Explanation For Sample Input 1 :
For first test case :

Reversing nodes 2 and 3 : 2 3
Resultant linked list : 1 2 3 4 6 5   

For second test case :

Reversing nodes 2 and 4 : 4 7 3
Resultant linked list : 1 4 7 3  
Sample Input 2 :
2
1 3 4 5 -1
1 2
1 2 2 -1
2 3
Sample Output 2 :
3 1 4 5
1 2 2
Reset Code
Full screen
copy-code
Console