VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-alternate-k-nodes-in-a-singly-linked-list/

⇱ Reverse alternate K nodes in a Singly Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse alternate K nodes in a Singly Linked List

Last Updated : 23 Jul, 2025

Given a linked list, The task is to reverse alternate k nodes. If the number of nodes left at the end of the list is fewer than k, reverse these remaining nodes or leave them in their original order, depending on the alternation pattern.

Example:

Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 2
Output: 2 -> 1 -> 3 -> 4 -> 6 -> 5 -> NULL.

👁 Insert-in-Sorted-way-in-a-Sorted-DLL-2-copy

Explanation :The nodes are reversed alternatively after 2 nodes.


Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> NULL, k = 3
Output: 3 -> 2 -> 1 -> 4 -> 5 -> 6 -> 8 -> 7-> NULL.

👁 Insert-in-Sorted-way-in-a-Sorted-DLL-4-copy

Explanation :The nodes are reversed alternatively after 3 nodes.

[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space:

The idea is to use recursive approach which involves reversing the first k nodes , skipping the subsequent k nodes, and then applying the same logic to the remaining portion of the list. By recursively calling the function on each segment, we ensure that the alternation pattern is maintained.

Below is the implementation of the above approach:


Output
2 1 3 4 6 5 

Time Complexity: O(n) , where n is the number of nodes in the linked list.
Auxiliary Space: O(n)

[Expected Approach - 2] Using Iterative Method - O(n) Time and O(1) Space:

The idea is similar to the recursive approach , instead we are traversing the linkedlist iteratively. We'll keep reversing the k nodes and skiping the next k nodes untill we still have nodes to process.

Step by Step Approach:

  • Initialize Pointers, prevTail (Tail of the previous segment) , curr (Current node being processed) and rev (Flag to indicate if the segment should be reversed).
  • Traverse the list using the curr pointer while there are still nodes to process:
    • If rev flag is True , reverse the next k nodes, then connect the reversed segment to prevTail. if the prevTail pointer is NULL , the actual head pointer will point to prevtail representing the newhead of final list.
    • else skip the next k nodes by updating prevTail.
    • Toggle the rev flag to perform alternate reversal.

Below is the implementation of the above approach:


Output
2 1 3 4 6 5 

Time Complexity: O(n) , where n is the number of nodes in the linked list.
Auxiliary Space: O(1)

Comment
Article Tags: