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.

AnswerBot
4mo
Reverse a linked list in groups of size K.
Iterate through the linked list in groups of size K.
Reverse each group of nodes.
Handle cases where the number of elements in the last group is less than K.
Help your peers!
Add answer anonymously...
Top Software Developer Intern Interview Questions Asked at Josh Technology Group
Q. Given a linked list, how do you ensure that it is in decreasing order?
Q. Given a random node in a BST, how do you check if a given element is part of the...read more
Q. Merge Two Binary Trees Problem Statement You are given the roots of two binary t...read more
Interview Questions Asked to Software Developer Intern at Other Companies
Top Skill-Based Questions for Josh Technology Group Software Developer Intern
Algorithms Interview Questions and Answers
250 Questions
Data Structures Interview Questions and Answers
250 Questions
Web Development Interview Questions and Answers
250 Questions
Operating Systems Interview Questions and Answers
250 Questions
System Design Interview Questions and Answers
250 Questions
C++ Interview Questions and Answers
150 Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

