Reverse a Linked List in groups of given size. | Practice | GeeksforGeeks

Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed (See Example 2 for clarification).
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
K = 4
Output: 4 2 2 1 8 7 6 5 
Explanation: 
The first 4 elements 1,2,2,4 are reversed first 
and then the next 4 elements 5,6,7,8. Hence, the 
resultant linked list is 4->2->2->1->8->7->6->5.

Example 2:
Input:
LinkedList: 1->2->3->4->5
K = 3
Output: 3 2 1 5 4 
Explanation: 
The first 3 elements are 1,2,3 are reversed 
first and then elements 4,5 are reversed.Hence, 
the resultant linked list is 3->2->1->5->4.

Your Task:
You don't need to read input or print anything. Your task is to complete the function reverse() which should reverse the linked list in group of size k and return the head of the modified linked list.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
0
yw0z81sl8pirjq7u6r2ti6ctdqdgrmfgb0qwqvx01 day ago
    public static Node reverse(Node node, int k)   {       //Your code here     Node curr=node, next=null, prev=null;     int i=0;     while(i<k && curr!=null){         next=curr.next;         curr.next=prev;         prev=curr;         curr=next;         i++;     }     if(next!=null){         node.next=reverse(next,k);     }     return prev;   } 
0
yuvrajranabtcse202 days ago
 c++ time o(n) space o(n)
 
if (k==1)return head;  //for length 1 no change happen
  node *go=head;   int count=0;   vector<vector<int>> ques;vector<int> ques1;       while(go!=NULL){       ques1.push_back(go->data);       go=go->next;       count+=1;       if(count==k){           ques.push_back(ques1);           ques1.clear();       count=0;}          }//vector is made with element in grp with k element in each   node *goo=head;   if(!ques1.empty())ques.push_back(ques1);   for(int i=0;i<ques.size();i++){       for(int j=ques[i].size()-1;j>=0;j--){           goo->data=ques[i][j];           goo=goo->next;       }   }   return head;   }
0
criticaugen2 days ago
#A simple approach using python 3
    def reverse(self, head, k):       current = head       next = None       prev = None       count = 0              while (current is not None and count < k):           # reversing k elements           next = current.next              # store the value of next node           current.next = prev              # reverse the link           prev = current                   # update previous           current = next                   # update current           count += 1              if next is not None:    # checking if there are more nodes ahead           head.next = self.reverse(next, k)     # reversing them by recursive              return prev 
0
bhavinraichura282 days ago
c++
class Solution{   public:   struct node *reverse (struct node *head, int k)   {        // Complete this method      struct node *h2= NULL;      struct node *prev = head;      struct node *curr= NULL;            int i=0;       while(head!=NULL && i<k){                   head = head -> next;            prev->next=h2;           h2= prev;           if (curr== NULL)               curr=h2;           prev=head;           i++;       }       if (head!=NULL)           curr->next=(reverse(head,k));       return h2;          }};
0
harshit849
This comment was deleted.
0
ishitavashisht20001 week ago
don't know why this approach is not working
class Solution{   public:   node* reverse(node* root){        struct node* prev=NULL;        struct node* cur=root;        struct node* nex;       while(cur){           nex=cur->next;           cur->next=prev;           prev=cur;           cur=nex;       }       return prev;   }   public:   struct node *reverse (struct node *head, int k)   {   int i=1;       struct node* temp_1=head;       struct node* temp_2;       while(i<k-1){           temp_1=temp_1->next;       }       temp_2=temp_1->next;       temp_1->next=NULL;       reverse(head);       reverse(temp_2);       struct node* t=head;       while(t->next!=NULL){           t=t->next;       }       t->next=temp_2;       return head;              // Complete this method   }};
0
ashutoshm200685ca2 weeks ago
CPP SOLUTION USING STACK
 
 struct node *reverse (struct node *head, int k)   {         node*newHead = NULL,*newtemp = NULL;        stack<int>s;        node*temp = head;                while(temp != NULL)        {            int p = 0;            while(p != k)            {                s.push(temp -> data);                temp = temp -> next;                p++;                if(temp == NULL)                break;            }                        while(!s.empty())            {                node*x = new node(s.top());                if(newHead == NULL)                {                    newHead = x;                    newtemp = newHead;                }                else                {                    newtemp -> next = x;                    newtemp = newtemp -> next;                }                s.pop();            }        }        delete head;        return newHead;   }
0
hritik1620012 weeks ago
Python recursive solution
``
class Solution:   def reverse(self,head, k):       def reverseList( head,k):                      if head is None:               return None           a = head           nextp = None           ab = k           while a:               ab-=1               if ab == 0 or not a.next:                    nextp = a.next                   a.next = None                   break               a = a.next                                            temp = head           prev = None           nextt = temp.next           while nextt:               prev = temp               temp = nextt               nextt  = nextt.next               temp.next = prev                      head.next = reverseList(nextp,k)           return temp                     non = 0       # tmp = None       # head1 = head       return  reverseList(head,k) ``
0
2001amitvats2 weeks ago
using stack 
 struct node *reverse (struct node *head, int k)   {        struct node*prev = NULL;       struct node*curr = head;       stack<node*>st;       while(curr!=NULL){           int count = 0;           while(curr!= NULL && count<k){               st.push(curr);               curr=curr->next;               count++;           }           while(st.size()>0){               if(prev == NULL){                   prev = st.top();                   head = prev;                   st.pop();               }               else{                   prev->next = st.top();                   prev = prev->next;                   st.pop();                                  }           }       }       prev->next = NULL;       return head;          }}; 
+3
harshscode2 weeks ago
 struct  node *cur=head;       struct  node *prev=NULL;       struct  node *ne=NULL;      int c=0;      while(cur and c<k)      {          ne=cur->next;          cur->next=prev;          prev=cur;          cur=ne;          c++;      }      if(ne!=NULL)      {          head->next=reverse(ne,k);      }      return prev;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.