Reverse Alternate K Nodes Problem Statement

You are given a singly linked list of integers along with a positive integer 'K'. The task is to modify the linked list by reversing every alternate 'K' nodes of the linked list.

Explanation:

A singly linked list is a type of linked list that allows traversal in only one direction from the head to the tail node.

Input:

The input consists of multiple test cases. For each test case, the first line contains elements of the singly linked list separated by a space, ending with -1. Note -1 is not a list element.
The second line contains the positive integer 'K'.

Output:

For each test case, return the modified linked list by reversing every alternate K nodes. The output should be space-separated elements terminated by -1.

Example:

Input: 
Linked list: 5 6 7 8 9 10 11 12
K: 3

Output:
7 6 5 8 9 10 12 11 -1

Explanation:
Reverse the first 'K' (3) nodes, then skip the next 'K' (3) nodes. Since only 2 nodes are left, which is less than 'K', reverse them. The resulting list is: 7 6 5 8 9 10 12 11.
  • Constraints:
  • 1 ≤ T ≤ 10
  • 1 ≤ N ≤ 5 * 104
  • 1 ≤ K ≤ N
  • -103 ≤ data ≤ 103, with data ≠ -1

Note: Implement the given function. Printing is handled automatically.

AnswerBot
4d

The task is to modify a singly linked list by reversing every alternate 'K' nodes of the linked list.

  • Iterate through the linked list in groups of size K, reverse every alternate group

  • Handle cases wher...read more

Help your peers!
Add answer anonymously...
Paytm Senior Software Engineer 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