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’.
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.
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?2
1 3 2 4 6 5 -1
2 3
1 3 7 4 -1
2 4
1 2 3 4 6 5
1 4 7 3
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
2
1 3 4 5 -1
1 2
1 2 2 -1
2 3
3 1 4 5
1 2 2
Traverse till the node at position ‘LOW’ recursively and then reverse the linked list.
The basic idea is to traverse the linked list recursively until we reach ‘LOW’ in our linked list. Then we will reverse the linked list by changing the pointers.
Here is the algorithm :
O(N), where ‘N’ is the number of nodes in the linked list.
We traverse the linked list once recursively to reverse the linked list. Therefore, the overall time complexity will be O(N).
O(N), where ‘N’ is the number of nodes in the linked list.
The recursive stack can contain the length of the linked list. Therefore, the overall space complexity will be O(N).