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.
[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:
C++
// C++ program to reverse alternate// k nodes in a linked list#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=NULL;}};// Reverses alternate k nodes and returns // the pointer to the new head nodeNode*kAltReverse(Node*head,intk){Node*curr=head;Node*next=NULL;Node*prev=NULL;intcount=0;// Reverse the first k nodes of the linked listwhile(curr!=NULL&&count<k){next=curr->next;curr->next=prev;prev=curr;curr=next;count++;}// Now head points to the kth node. // So change next of head to (k+1)th nodeif(head!=NULL){head->next=curr;}// Skip the next k nodescount=0;while(count<k-1&&curr!=NULL){curr=curr->next;count++;}// Recursively call for the list // starting from curr->nextif(curr!=NULL){curr->next=kAltReverse(curr->next,k);}// prev is the new head of the input listreturnprev;}voidprintList(Node*node){Node*curr=node;while(curr!=NULL){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Hardcoded linked list: 1->2->3->4->5->6Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head->next->next->next->next->next=newNode(6);head=kAltReverse(head,2);printList(head);return0;}
C
// C program to reverse alternate // k nodes in a linked list#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Reverses alternate k nodes and returns // the pointer to the new head nodestructNode*kAltReverse(structNode*head,intk){structNode*curr=head;structNode*next=NULL;structNode*prev=NULL;intcount=0;// Reverse the first k nodes of the linked listwhile(curr!=NULL&&count<k){next=curr->next;curr->next=prev;prev=curr;curr=next;count++;}// Now head points to the kth node. // So change next of head to (k+1)th nodeif(head!=NULL){head->next=curr;}// Skip the next k nodescount=0;while(count<k-1&&curr!=NULL){curr=curr->next;count++;}// Recursively call for the list // starting from curr->nextif(curr!=NULL){curr->next=kAltReverse(curr->next,k);}// prev is the new head of the input listreturnprev;}voidprintList(structNode*node){structNode*curr=node;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}intmain(){// Hardcoded linked list: 1->2->3->4->5->6structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);head->next->next->next->next->next=createNode(6);head=kAltReverse(head,2);printList(head);return0;}
Java
// Java program to reverse alternate // k nodes in a linked listclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Reverses alternate k nodes and returns // the pointer to the new head nodestaticNodekAltReverse(Nodehead,intk){Nodecurr=head;Nodenext=null;Nodeprev=null;intcount=0;// Reverse the first k nodes of the linked listwhile(curr!=null&&count<k){next=curr.next;curr.next=prev;prev=curr;curr=next;count++;}// Now head points to the kth node. // So change next of head to (k+1)th nodeif(head!=null){head.next=curr;}// Skip the next k nodescount=0;while(count<k-1&&curr!=null){curr=curr.next;count++;}// Recursively call for the list // starting from curr->nextif(curr!=null){curr.next=kAltReverse(curr.next,k);}// prev is the new head of // the input listreturnprev;}staticvoidprintList(Nodenode){Nodecurr=node;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Hardcoded linked list: 1->2->3->4->5->6Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);head=kAltReverse(head,2);printList(head);}}
Python
# Python program to reverse alternate # k nodes in a linked listclassNode:def__init__(self,x):self.data=xself.next=None# Reverses alternate k nodes and returns # the pointer to the new head nodedefkAltReverse(head,k):curr=headnext=Noneprev=Nonecount=0# Reverse the first k nodes of the linked listwhilecurrisnotNoneandcount<k:next=curr.nextcurr.next=prevprev=currcurr=nextcount+=1# Now head points to the kth node. # So change next of head to (k+1)th nodeifheadisnotNone:head.next=curr# Skip the next k nodescount=0whilecount<k-1andcurrisnotNone:curr=curr.nextcount+=1# Recursively call for the list # starting from curr->nextifcurrisnotNone:curr.next=kAltReverse(curr.next,k)# prev is the new head of the input listreturnprevdefprintList(node):curr=nodewhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Hardcoded linked list: 1->2->3->4->5->6head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head.next.next.next.next.next=Node(6)head=kAltReverse(head,2)printList(head)
C#
// C# program to reverse alternate// k nodes in a linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Reverses alternate k nodes and returns // the pointer to the new head nodestaticNodekAltReverse(Nodehead,intk){Nodecurr=head;Nodenext=null;Nodeprev=null;intcount=0;// Reverse the first k nodes of the linked listwhile(curr!=null&&count<k){next=curr.next;curr.next=prev;prev=curr;curr=next;count++;}// Now head points to the kth node. // So change next of head to (k+1)th nodeif(head!=null){head.next=curr;}// Skip the next k nodescount=0;while(count<k-1&&curr!=null){curr=curr.next;count++;}// Recursively call for the list // starting from curr->nextif(curr!=null){curr.next=kAltReverse(curr.next,k);}// prev is the new head of the input listreturnprev;}staticvoidprintList(Nodenode){Nodecurr=node;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){// Hardcoded linked list: 1->2->3->4->5->6Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);head=kAltReverse(head,2);printList(head);}}
JavaScript
// JavaScript program to reverse alternate k// nodes in a linked listclassNode{constructor(x){this.data=x;this.next=null;}}// Reverses alternate k nodes and returns // the pointer to the new head nodefunctionkAltReverse(head,k){letcurr=head;letnext=null;letprev=null;letcount=0;// Reverse the first k nodes of the// linked listwhile(curr!==null&&count<k){next=curr.next;curr.next=prev;prev=curr;curr=next;count++;}// Now head points to the kth node. // So change next of head to (k+1)th nodeif(head!==null){head.next=curr;}// Skip the next k nodescount=0;while(count<k-1&&curr!==null){curr=curr.next;count++;}// Recursively call for the list // starting from curr->nextif(curr!==null){curr.next=kAltReverse(curr.next,k);}// prev is the new head of // the input listreturnprev;}functionprintList(node){letcurr=node;while(curr!==null){console.log(curr.data+" ");curr=curr.next;}console.log();}// Hardcoded linked list: 1->2->3->4->5->6lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);head=kAltReverse(head,2);printList(head);
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:
C++
// C++ program to reverse alternate k nodes#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=NULL;}};Node*kAltReverse(Node*head,intk){// Pointer to the tail of the// previous segmentNode*prevTail=NULL;boolrev=true;Node*curr=head;while(curr!=NULL){// Reverse the next k nodesif(rev==true){// Mark the head of the// current segmentNode*segHead=curr;Node*prev=NULL;// Reverse the current segment of k nodesfor(inti=0;i<k&&curr!=NULL;i++){Node*nxt=curr->next;curr->next=prev;prev=curr;curr=nxt;}// Update the head of the list if this // is the first segmentif(prevTail==NULL){head=prev;}else{// Link previous segment with the // current reversed segmentprevTail->next=prev;}// Update the tail of the current segmentprevTail=segHead;rev=false;}else{// Skip the next k nodes without reversingprevTail->next=curr;for(inti=0;i<k&&curr!=NULL;i++){prevTail=curr;curr=curr->next;}rev=true;}}returnhead;}voidprintList(Node*node){Node*curr=node;while(curr!=NULL){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Hardcoded linked list:// 1->2->3->4->5->6Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);head->next->next->next->next->next=newNode(6);head=kAltReverse(head,2);printList(head);return0;}
C
// C program to reverse alternate k nodes#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*kAltReverse(structNode*head,intk){// Pointer to the tail of the// previous segmentstructNode*prevTail=NULL;intrev=1;structNode*curr=head;while(curr!=NULL){// Reverse the next k nodesif(rev==1){// Mark the head of the current segmentstructNode*segHead=curr;structNode*prev=NULL;// Reverse the current segment of k nodesfor(inti=0;i<k&&curr!=NULL;i++){structNode*nxt=curr->next;curr->next=prev;prev=curr;curr=nxt;}// Update the head of the list if // this is the first segmentif(prevTail==NULL){head=prev;}else{// Link previous segment with the // current reversed segmentprevTail->next=prev;}// Update the tail of the current segmentprevTail=segHead;rev=0;}else{// Skip the next k nodes without reversingprevTail->next=curr;for(inti=0;i<k&&curr!=NULL;i++){prevTail=curr;curr=curr->next;}rev=1;}}returnhead;}voidprintList(structNode*node){structNode*curr=node;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}intmain(){// Hardcoded linked list: 1->2->3->4->5->6structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);head->next->next->next->next=createNode(5);head->next->next->next->next->next=createNode(6);head=kAltReverse(head,2);printList(head);return0;}
Java
// Java program to reverse alternate// k nodes in a linked listclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{staticNodekAltReverse(Nodehead,intk){// Pointer to the tail of the// previous segmentNodeprevTail=null;booleanrev=true;Nodecurr=head;while(curr!=null){// Reverse the next k nodesif(rev==true){// Mark the head of the// current segmentNodesegHead=curr;Nodeprev=null;// Reverse the current// segment of k nodesfor(inti=0;i<k&&curr!=null;i++){Nodenxt=curr.next;curr.next=prev;prev=curr;curr=nxt;}// Update the head of the list// if this is the first segmentif(prevTail==null){head=prev;}else{// Link previous segment with the// current reversed segmentprevTail.next=prev;}// Update the tail of the// current segmentprevTail=segHead;rev=false;}else{// Skip the next k nodes// without reversingprevTail.next=curr;for(inti=0;i<k&&curr!=null;i++){prevTail=curr;curr=curr.next;}rev=true;}}returnhead;}staticvoidprintList(Nodenode){Nodecurr=node;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Hardcoded linked list: 1->2->3->4->5->6Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);head=kAltReverse(head,2);printList(head);}}
Python
# Python program to reverse alternate k nodesclassNode:def__init__(self,x):self.data=xself.next=NonedefkAltReverse(head,k):# Pointer to the tail of the# previous segmentprev_tail=Nonerev=Truecurr=headwhilecurr:# Reverse the next k nodesifrev==True:# Mark the head of the current segmentseg_head=currprev=None# Reverse the current segment of k nodesfor_inrange(k):ifcurrisNone:breaknxt=curr.nextcurr.next=prevprev=currcurr=nxt# Update the head of the list # if this is the first segmentifprev_tailisNone:head=prevelse:# Link previous segment with# the current reversed segmentprev_tail.next=prev# Update the tail of the current segmentprev_tail=seg_headrev=Falseelse:# Skip the next k nodes without reversingprev_tail.next=currfor_inrange(k):ifcurrisNone:breakprev_tail=currcurr=curr.nextrev=Truereturnheaddefprint_list(node):curr=nodewhilecurr:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Hardcoded linked list: 1->2->3->4->5->6head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)head.next.next.next.next.next=Node(6)head=kAltReverse(head,2)print_list(head)
C#
// C# program to reverse alternate k nodesusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{staticNodekAltReverse(Nodehead,intk){// Pointer to the tail of the previous segmentNodeprevTail=null;boolrev=true;Nodecurr=head;while(curr!=null){// Reverse the next k nodesif(rev==true){// Mark the head of the current segmentNodesegHead=curr;Nodeprev=null;// Reverse the current segment of k nodesfor(inti=0;i<k&&curr!=null;i++){Nodenxt=curr.next;curr.next=prev;prev=curr;curr=nxt;}// Update the head of the list if this is// the first segmentif(prevTail==null){head=prev;}else{// Link previous segment with the// current reversed segmentprevTail.next=prev;}// Update the tail of the current segmentprevTail=segHead;rev=false;}else{// Skip the next k nodes without reversingprevTail.next=curr;for(inti=0;i<k&&curr!=null;i++){prevTail=curr;curr=curr.next;}rev=true;}}returnhead;}staticvoidprintList(Nodenode){Nodecurr=node;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){// Hardcoded linked list: 1->2->3->4->5->6Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);head=kAltReverse(head,2);printList(head);}}
JavaScript
// Javascript program to reverse // alternate k nodesclassNode{constructor(x){this.data=x;this.next=null;}}functionkAltReverse(head,k){// Pointer to the tail of // the previous segmentletprevTail=null;letrev=true;letcurr=head;while(curr!==null){// Reverse the next k nodesif(rev==true){// Mark the head of the current segmentletsegHead=curr;letprev=null;// Reverse the current segment of k nodesfor(leti=0;i<k&&curr!==null;i++){letnxt=curr.next;curr.next=prev;prev=curr;curr=nxt;}// Update the head of the list if this is the// first segmentif(prevTail===null){head=prev;}else{// Link previous segment with the current// reversed segmentprevTail.next=prev;}// Update the tail of the current segmentprevTail=segHead;rev=false;}else{// Skip the next k nodes without reversingprevTail.next=curr;for(leti=0;i<k&&curr!==null;i++){prevTail=curr;curr=curr.next;}rev=true;}}returnhead;}functionprintList(node){letcurr=node;while(curr!==null){console.log(curr.data);curr=curr.next;}console.log();}// Hardcoded linked list: 1->2->3->4->5->6lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);head.next.next.next.next.next=newNode(6);head=kAltReverse(head,2);printList(head);
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)