# Reverse a singly Linked List in groups of given size | Set 4 (Space efficient approach)

• Last Updated : 26 Nov, 2021

Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples:

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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

Multiple approaches for the above problem have been already discussed in the posts below:

Approach: This article focus on an approach that uses O(1) auxiliary space. Below are the steps to follow:

• Keep track of the first node in a pointer for each group of k elements in the linked list.
• Reverse the order of the next k elements from the first node of the current group using this algorithm.
• After reversing, the first node of the current group will become the last node. Connect it with the k+1th node of the linked list.
• The k+1th node will become the first node of the next group of k elements. Similarly, repeat the process for every group of k elements till the whole linked list has been traversed.

Below is the implementation of the above approach:

## C++

 `// C++ program to reverse a linked``// list in groups of given size``#include ``using` `namespace` `std;` `    ``// Linked list Node``   ``class` `Node {``    ``public``:``        ``int` `data;``        ``Node* next;``        ``Node(``int` `d)``        ``{``            ``data = d;``            ``next = NULL;``        ``}``    ``};`` `  `    ``void` `reverse(Node** node, ``int` `k)``    ``{``        ``if` `(k == 1)``            ``return``;` `        ``// Keeps track of the final list``        ``Node* result = NULL;` `        ``// Append a new node at initial step``        ``Node* head = ``new` `Node(0);``        ``head->next = *(node);``        ``Node* next = (*node)->next;` `        ``int` `count = 0;``        ``while` `(next) {``            ``count++;` `            ``// Update the pointer and``            ``// iterate linked list by``            ``// using node & next pointer``            ``Node* tmp = next->next;``            ``next->next = *(node);``            ``*(node) = next;``            ``next = tmp;` `            ``if` `(count == k - 1) {``                ``count = 0;` `                ``if` `(result == NULL)``                    ``result = *(node);` `                ``// Last step to join the``                ``// reversed k-group with``                ``// the linked list``                ``tmp = head->next;``                ``tmp->next = next;``                ``head->next = *(node);``                ``head = tmp;` `                ``// Move on to the next k-group``                ``*(node) = next;``                ``if` `(*(node)!= NULL)``                    ``next = (*node)->next;``            ``}``        ``}` `        ``// Process last elements``        ``Node* tmp = head->next;``        ``if` `(tmp)``            ``tmp->next = NULL;``        ``head->next = *(node);``      ` `      ``*(node) = result;``        ``return``;``    ``}` `    ``// Utility functions` `    ``// Function to inserts a new``    ``// Node at front of the list` `    ``void` `push(Node** head,``int` `new_data)``    ``{``        ``Node* new_node = ``new` `Node(new_data);``        ``new_node->next = *(head);``        ``*(head) = new_node;``    ``}` `    ``// Function to print linked list``    ``void` `printList(Node** head)``    ``{``        ``Node* temp = *(head);``        ``while` `(temp) {``            ``cout << temp->data << ``" "``;``            ``temp = temp->next;``        ``}``        ``cout << endl;``    ``}` `/* Driver program to test above functions */` `int` `main()``{``    ``Node* head = NULL;` `    ``/* Constructed Linked List is``     ``* 1->2->3->4->5->6->7->8->null */``    ``push(&head,8);``    ``push(&head,7);``    ``push(&head,6);``    ``push(&head,5);``    ``push(&head,4);``    ``push(&head,3);``    ``push(&head,2);``    ``push(&head,1);` `    ``reverse(&head, 3);``    ``printList(&head);` `    ``return` `0;``}` `// This code is contributed by maddler.`

## Java

 `// Java program to reverse a linked``// list in groups of given size` `class` `LinkedList {` `    ``// head of list``    ``Node head;` `    ``// Linked list Node``    ``class` `Node {``        ``int` `data;``        ``Node next;``        ``Node(``int` `d)``        ``{``            ``data = d;``            ``next = ``null``;``        ``}``    ``}` `    ``Node reverse(Node node, ``int` `k)``    ``{``        ``if` `(k == ``1``)``            ``return` `node;` `        ``// Keeps track of the final list``        ``Node result = ``null``;` `        ``// Append a new node at initial step``        ``Node head = ``new` `Node(``0``);``        ``head.next = node;``        ``Node next = node.next;` `        ``int` `count = ``0``;``        ``while` `(next != ``null``) {``            ``count++;` `            ``// Update the pointer and``            ``// iterate linked list by``            ``// using node & next pointer``            ``Node tmp = next.next;``            ``next.next = node;``            ``node = next;``            ``next = tmp;` `            ``if` `(count == k - ``1``) {``                ``count = ``0``;` `                ``if` `(result == ``null``)``                    ``result = node;` `                ``// Last step to join the``                ``// reversed k-group with``                ``// the linked list``                ``tmp = head.next;``                ``tmp.next = next;``                ``head.next = node;``                ``head = tmp;` `                ``// Move on to the next k-group``                ``node = next;``                ``if` `(node != ``null``)``                    ``next = node.next;``            ``}``        ``}` `        ``// Process last elements``        ``Node tmp = head.next;``        ``if` `(tmp != ``null``)``            ``tmp.next = ``null``;``        ``head.next = node;` `        ``return` `result;``    ``}` `    ``// Utility functions` `    ``// Function to inserts a new``    ``// Node at front of the list``    ``public` `void` `push(``int` `new_data)``    ``{``        ``Node new_node = ``new` `Node(new_data);``        ``new_node.next = head;``        ``head = new_node;``    ``}` `    ``// Function to print linked list``    ``void` `printList()``    ``{``        ``Node temp = head;``        ``while` `(temp != ``null``) {``            ``System.out.print(temp.data + ``" "``);``            ``temp = temp.next;``        ``}``        ``System.out.println();``    ``}` `    ``/* Driver program to test above functions */``    ``public` `static` `void` `main(String args[])``    ``{``        ``LinkedList llist = ``new` `LinkedList();` `        ``/* Constructed Linked List is``         ``* 1->2->3->4->5->6->7->8->null */``        ``llist.push(``8``);``        ``llist.push(``7``);``        ``llist.push(``6``);``        ``llist.push(``5``);``        ``llist.push(``4``);``        ``llist.push(``3``);``        ``llist.push(``2``);``        ``llist.push(``1``);` `        ``llist.head = llist.reverse(llist.head, ``3``);``        ``llist.printList();``    ``}``}`

## C#

 `using` `System;` `// C# program to reverse a linked``// list in groups of given size``public` `class` `List {` `    ``// head of list``    ``public` `Node head;` `    ``// Linked list Node``    ``public` `class` `Node {``    ``public`     `int` `data;``    ``public`     `Node next;` `    ``public`     `Node(``int` `d) {``            ``data = d;``            ``next = ``null``;``        ``}``    ``}` `    ``Node reverse(Node node, ``int` `k) {``        ``if` `(k == 1)``            ``return` `node;` `        ``// Keeps track of the readonly list``        ``Node result = ``null``;` `        ``// Append a new node at initial step``        ``Node head = ``new` `Node(0);``        ``head.next = node;``        ``Node next = node.next;` `        ``int` `count = 0;``        ``while` `(next != ``null``) {``            ``count++;` `            ``// Update the pointer and``            ``// iterate linked list by``            ``// using node & next pointer``            ``Node tmp1 = next.next;``            ``next.next = node;``            ``node = next;``            ``next = tmp1;` `            ``if` `(count == k - 1) {``                ``count = 0;` `                ``if` `(result == ``null``)``                    ``result = node;` `                ``// Last step to join the``                ``// reversed k-group with``                ``// the linked list``                ``tmp1 = head.next;``                ``tmp1.next = next;``                ``head.next = node;``                ``head = tmp1;` `                ``// Move on to the next k-group``                ``node = next;``                ``if` `(node != ``null``)``                    ``next = node.next;``            ``}``        ``}` `        ``// Process last elements``        ``Node tmp = head.next;``        ``if` `(tmp != ``null``)``            ``tmp.next = ``null``;``        ``head.next = node;` `        ``return` `result;``    ``}` `    ``// Utility functions` `    ``// Function to inserts a new``    ``// Node at front of the list``    ``public` `void` `Push(``int` `new_data) {``        ``Node new_node = ``new` `Node(new_data);``        ``new_node.next = head;``        ``head = new_node;``    ``}` `    ``// Function to print linked list``    ``void` `printList() {``        ``Node temp = head;``        ``while` `(temp != ``null``) {``            ``Console.Write(temp.data + ``" "``);``            ``temp = temp.next;``        ``}``        ``Console.WriteLine();``    ``}` `    ``/* Driver program to test above functions */``    ``public` `static` `void` `Main(String []args)``    ``{``        ``List llist = ``new` `List();` `        ``/*``         ``* Constructed Linked List is 1->2->3->4->5->6->7->8->null``         ``*/``        ``llist.Push(8);``        ``llist.Push(7);``        ``llist.Push(6);``        ``llist.Push(5);``        ``llist.Push(4);``        ``llist.Push(3);``        ``llist.Push(2);``        ``llist.Push(1);` `        ``llist.head = llist.reverse(llist.head, 3);``        ``llist.printList();``    ``}``}` `// This code is contributed by gauravrajput1`
Output
`3 2 1 6 5 4 8 7 `

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up