Reverse List In K Groups

You are given a linked list of 'N' nodes and an integer 'K'. You have to reverse the given linked list in groups of size K i.e if the list contains x nodes numbered from 1 to x, then you need to reverse each of the groups (1,K),(K+1,2*K), and so on.

For example, if the list is [1, 2, 3, 4, 5, 6] and K = 2, then the new list will be [2, 1, 4, 3, 6, 5].

Note:
1. In case the number of elements in the last cannot be evenly divided into groups of size k, then just reverse the last group(with any size). For example if the list is 1 2 3 4 5 and K = 3, then the answer would be 3 2 1 5 4.

2. All the node values will be distinct.
Input Format:
The first line of input contains an integer 'T' representing the number of test cases. Then T test cases follow.

The first line of each test case contains a Linked list whose elements are separated by space and the linked list is terminated by -1.

The second line of each test case contains an integer K.
Output Format:
 For each test case print the elements of  modified linked list separated by space..

The output of each test case will be printed in a separate line.

Note:

You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100   
1 <= N <= 10^4
1 <= K <= 10^4

Time Limit: 1sec
CodingNinjas
author
2y

Step 1 : We first traverse till kth node, keep track of next node and call function to reverse the first k nodes
Step 2 : For reversing we use 3 pointers to reverse the linkedlist

CodingNinjas
author
2y
Recursive Approach
  • We can use recursion to solve this problem.
  • The main idea is to reverse the first ‘K’ nodes by ourselves and let the recursive function reverse the rest of the linked list.
  • Let reverse...read more
CodingNinjas
author
2y
Iterative Approach
  • Since we have to optimize on space, instead of using recursion we can use some pointers to create the links between the different sets of 'K' nodes.
  • First of all we have to create som...read more
Add answer anonymously...
Josh Technology Group Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter