


You need to perform swapping of nodes in the given linked list. Do not swap the values.
If the given list is:[1 -> 4 -> 5 -> 6 -> 9 -> NULL] and ‘K’ is 2, then after swapping 2nd node from the start i.e, 4 with 2nd node from the end i.e, 6 we get the final list as: [1 -> 6 -> 5 -> 4 -> 9 -> NULL].
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains a single integer ‘K’ which denotes the position of the nodes to be swapped.
The second line of each test case contains space-separated integers denoting the values of nodes of the Linked List. The Linked List is terminated with -1.
For each test case, print “CORRECT” if the nodes are swapped in the given list. Otherwise, print “INCORRECT”.
Print the output of each test case in a separate line.
1 <= T <= 10
1 <= N <= 10 ^ 6
-10^9 <= Node.Data <= 10^9 and Node.Data != -1
1 <= K <= N
The linked list is 1-indexed.
Time Limit: 1 sec
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
In this approach, we will use two pointers, say begin and end. We will also use two other nodes prevBegin and prevEnd, to store the previous begin and end node, respectively. The variable begin would point to the kth node from the beginning, and the end would point to the kth node from the end. To find the position of the begin we will traverse the list up to the k node. To find the end position, we will first find the length of the list and then traverse up to (length of the list - k) nodes.
Then, we will swap the node pointed by the begin with the node pointed by the end by breaking old links and creating new links.
Algorithm:
This approach is the same as the above. The difference is that instead of iterating the list thrice in this approach, we will iterate it twice. While finding the length of the list, when we come across the (k - 1)th node, we will set prevBegin equal to it, and when we come across the kth node, we will set begin equal to it.
Algorithm:
This approach is also the same as the above. The difference is that we will iterate only once instead of iterating the list twice in this approach. The method of finding the position of begin will be the same as above. To find the end position, we will use the fact that if a node says n1 is exactly k nodes behind another node n2, then when the node n2 reaches the end, the node n1 will still be k nodes behind, i.e., at the kth node from the end.
Algorithm: