Reverse Linked List in Groups of K
You are provided with a linked list containing 'N' nodes and an integer 'K'. The task is to reverse the linked list in groups of size K, which means reversing the nodes in each group (1,K),(K+1,2*K), etc.
Example:
Input:
List: [1, 2, 3, 4, 5, 6], K = 2
Output:
[2, 1, 4, 3, 6, 5]
Explanation:
The nodes are reversed in pairs: [1, 2] -> [2, 1], [3, 4] -> [4, 3], [5, 6] -> [6, 5].
Constraints:
- 1 <= T <= 100
- 1 <= N <= 10^4
- 1 <= K <= 10^4
- Time Limit: 1sec
Input:
The first line of input contains an integer 'T' representing the number of test cases. Each test case follows with:
1. A line containing a linked list where elements are separated by spaces and the list is terminated by -1.
2. A line containing the integer K.
Output:
For each test case, output the modified linked list elements, separated by spaces, on a new line.
Note:
- If the number of elements in the last group cannot be evenly divided by K, reverse that last group. For example, for list [1, 2, 3, 4, 5] and K = 3, the output is [3, 2, 1, 5, 4].
- All node values in the linked list are distinct.
Be the first one to answer
Add answer anonymously...
Top Info Edge Senior Software Engineer interview questions & answers
Popular interview questions of Senior Software Engineer
Top HR questions asked in Info Edge Senior Software Engineer
>
Info Edge Senior Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app