Reverse Doubly Linked List Nodes in Groups

You are given a doubly linked list of integers along with a positive integer K that represents the group size. Your task is to modify the linked list by reversing every group of K nodes. If the number of nodes left in the list or the last group is fewer than K, reverse those remaining nodes as well.

Input:

First line: Integer T, the number of test cases.
For each test case:
- First line: Elements of the doubly linked list separated by a single space, ending with -1 (indicating the end of the list; -1 is not a list element).
- Second line: Integer K.

Output:

For each test case, print the modified linked list with the elements separated by a single space, ending with -1.

Example:

Input:
Linked list: 8 9 10 11 12 K: 3
Output:
10 9 8 12 11 -1
Explanation:

Reverse the first 3 nodes, resulting in 10, 9, 8. The remaining 2 nodes (11 and 12) are fewer than 3, so they are reversed to 12, 11.

Constraints:

  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 5 × 104
  • 1 ≤ K ≤ 105
  • -103 ≤ data ≤ 103 and data ≠ -1
  • Time Limit: 1 sec
AnswerBot
2d

Reverse groups of K nodes in a doubly linked list.

  • Iterate through the linked list in groups of K nodes

  • Reverse each group of K nodes

  • Handle cases where the number of nodes is less than K

  • Update the point...read more

Help your peers!
Add answer anonymously...
TCS iON Technical Trainee 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

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