Reverse a Linked List in groups of given size (Iterative Approach)
Last Updated :
02 Jan, 2025
Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the 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.
Examples:
Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 2
Output: head: 2 -> 1 -> 4 -> 3 -> 6 -> 5 -> NULL
Explanation : Linked List is reversed in a group of size k = 2.
Input: head: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL, k = 4
Output: head: 4 -> 3 -> 2 -> 1 -> 6 -> 5 -> NULL
Explanation : Linked List is reversed in a group of size k = 4.
Approach:
To reverse a linked list in groups of size k, the goal is to traverse the list in segments of k nodes and reverse each group individually. After reversing each group, we connect it to the previous group by updating the tail pointer. This process continues until the entire list is traversed, and we return the new head of the reversed list.
Follow the steps below to solve the problem:
- Initialize pointers:
- Set curr to the head of the list to start traversing.
- Set newHead to NULL to track the new head after the first group reversal.
- Set tail to NULL to connect the previous group to the current reversed group.
- Traverse the list in groups of k:
- For each group of k nodes, set groupHead to curr.
- Reverse the nodes in the group by updating the next pointers, using prev and nextNode.
- Connect the reversed group to the previous one:
- After reversing, if tail is not nullptr, connect the previous group's end to the current reversed group’s head.
- Update tail to point to the last node of the current group.
- Repeat the process until all nodes in the list are processed, and return newHead, which points to the head of the fully reversed list
Below is the illustration of above approach:
C++
// C++ program to reverse a linked list
// in groups of given size
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int x) {
data = x;
next = nullptr;
}
};
// Function to reverse K groups
Node *reverseKGroup(Node *head, int k) {
if (head == nullptr) {
return head;
}
Node *curr = head;
Node *newHead = nullptr;
Node *tail = nullptr;
while (curr != nullptr) {
Node *groupHead = curr;
Node *prev = nullptr;
Node *nextNode = nullptr;
int count = 0;
// Reverse the nodes in the current group
while (curr != nullptr && count < k) {
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
count++;
}
// If newHead is null, set it to the
// last node of the first group
if (newHead == nullptr) {
newHead = prev;
}
// Connect the previous group to the
// current reversed group
if (tail != nullptr) {
tail->next = prev;
}
// Move tail to the end of the reversed group
tail = groupHead;
}
return newHead;
}
void printList(Node *head) {
Node *curr = head;
while (curr != nullptr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
// Creating a sample singly linked list:
// 1 -> 2 -> 3 -> 4 -> 5
Node *head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(5);
head = reverseKGroup(head, 3);
printList(head);
return 0;
}
C
// C program to reverse a linked list
// in groups of given size
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Function to reverse K groups
struct Node* reverseKGroup(struct Node* head, int k) {
if (head == NULL) {
return head;
}
struct Node* curr = head;
struct Node* newHead = NULL;
struct Node* tail = NULL;
while (curr != NULL) {
struct Node* groupHead = curr;
struct Node* prev = NULL;
struct Node* nextNode = NULL;
int count = 0;
// Reverse the nodes in the current group
while (curr != NULL && count < k) {
nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
count++;
}
// If newHead is null, set it to the
// last node of the first group
if (newHead == NULL) {
newHead = prev;
}
// Connect the previous group to the
// current reversed group
if (tail != NULL) {
tail->next = prev;
}
// Move tail to the end of the
// reversed group
tail = groupHead;
}
return newHead;
}
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
struct Node* createNode(int x) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->next = NULL;
return newNode;
}
int main() {
// Creating a sample singly linked list:
// 1 -> 2 -> 3 -> 4 -> 5
struct Node* 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 = reverseKGroup(head, 3);
printList(head);
return 0;
}
Java
// Java program to reverse a linked list
// in groups of given size
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to reverse K groups
static Node reverseKGroup(Node head, int k) {
if (head == null) {
return head;
}
Node curr = head;
Node newHead = null;
Node tail = null;
while (curr != null) {
Node groupHead = curr;
Node prev = null;
Node nextNode = null;
int count = 0;
// Reverse the nodes in the current group
while (curr != null && count < k) {
nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
count++;
}
// If newHead is null, set it to the
// last node of the first group
if (newHead == null) {
newHead = prev;
}
// Connect the previous group to the
// current reversed group
if (tail != null) {
tail.next = prev;
}
// Move tail to the end of the
// reversed group
tail = groupHead;
}
return newHead;
}
static void printList(Node head) {
Node curr = head;
while (curr != null) {
System.out.print(curr.data + " ");
curr = curr.next;
}
System.out.println();
}
public static void main(String[] args) {
// Creating a sample singly linked list:
// 1 -> 2 -> 3 -> 4 -> 5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head = reverseKGroup(head, 3);
printList(head);
}
}
Python
# Python program to reverse a linked list
# in groups of given size
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to reverse K groups
def reverseKGroup(head, k):
if head is None:
return head
curr = head
newHead = None
tail = None
while curr is not None:
groupHead = curr
prev = None
nextNode = None
count = 0
# Reverse the nodes in the current group
while curr is not None and count < k:
nextNode = curr.next
curr.next = prev
prev = curr
curr = nextNode
count += 1
# If newHead is null, set it to the
# last node of the first group
if newHead is None:
newHead = prev
# Connect the previous group to the
# current reversed group
if tail is not None:
tail.next = prev
# Move tail to the end of
# the reversed group
tail = groupHead
return newHead
def printList(head):
curr = head
while curr is not None:
print(curr.data, end=" ")
curr = curr.next
print()
if __name__ == "__main__":
# Creating a sample singly linked list:
# 1 -> 2 -> 3 -> 4 -> 5
head = 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 = reverseKGroup(head, 3)
printList(head)
C#
// C# program to reverse a linked list
// in groups of given size
using System;
class Node {
public int data;
public Node next;
public Node(int x) {
data = x;
next = null;
}
}
class GfG {
// Function to reverse K groups
static Node reverseKGroup(Node head, int k) {
if (head == null) {
return head;
}
Node curr = head;
Node newHead = null;
Node tail = null;
while (curr != null) {
Node groupHead = curr;
Node prev = null;
Node nextNode = null;
int count = 0;
// Reverse the nodes in the current group
while (curr != null && count < k) {
nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
count++;
}
// If newHead is null, set it to the
// last node of the first group
if (newHead == null) {
newHead = prev;
}
// Connect the previous group to the
// current reversed group
if (tail != null) {
tail.next = prev;
}
// Move tail to the end of the
// reversed group
tail = groupHead;
}
return newHead;
}
static void printList(Node head) {
Node curr = head;
while (curr != null) {
Console.Write(curr.data + " ");
curr = curr.next;
}
Console.WriteLine();
}
static void Main(string[] args) {
// Creating a sample singly linked list:
// 1 -> 2 -> 3 -> 4 -> 5
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head = reverseKGroup(head, 3);
printList(head);
}
}
JavaScript
// JavaScript program to reverse a linked list
// in groups of given size
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to reverse K groups
function reverseKGroup(head, k) {
if (head === null) {
return head;
}
let curr = head;
let newHead = null;
let tail = null;
while (curr !== null) {
let groupHead = curr;
let prev = null;
let nextNode = null;
let count = 0;
// Reverse the nodes in the current group
while (curr !== null && count < k) {
nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
count++;
}
// If newHead is null, set it to the
// last node of the first group
if (newHead === null) {
newHead = prev;
}
// Connect the previous group to the
// current reversed group
if (tail !== null) {
tail.next = prev;
}
// Move tail to the end of the
// reversed group
tail = groupHead;
}
return newHead;
}
function printList(head) {
let curr = head;
while (curr !== null) {
console.log(curr.data + " ");
curr = curr.next;
}
}
// Creating a sample singly linked list:
// 1 -> 2 -> 3 -> 4 -> 5
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head = reverseKGroup(head, 3);
printList(head);
Time complexity: O(n), where n is the number of nodes in linked list.
Auxiliary Space: O(1)
Related articles:
Similar Reads
Reverse a Linked List in groups of given size Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the 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.Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
3 min read
Reverse a singly Linked List in groups of given size (Recursive Approach) Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the 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.Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
9 min read
Reverse a doubly linked list in groups of given size | Set 2 Given a doubly-linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Input: List: 10<->8<->4<->2, K=2Output: 8<->10<->2<->4 Input: List: 1<->2<->3<->4<->5<->6<->7<->8, K=3O
15+ min read
XOR Linked List - Reverse a Linked List in groups of given size Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7< â > 6 < â > 8 < â > 11 < â > 3, K = 3 Output: 8 < â > 6 < â > 7 < â > 3 < â > 11 Explanation: Reversing first K(= 3)
13 min read
Reverse a Linked List in groups of given size using Deque Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the 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.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
8 min read
Reverse a doubly linked list in groups of K size Given a Doubly linked list containing n nodes. The task is to reverse every group of k nodes in the 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.Examples: Input: 1 <-> 2 <-> 3 <-> 4 <-
15+ min read
Reverse a Linked List in groups of given size using Stack Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the 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.Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
8 min read
Reverse given Linked List in groups of specific given sizes Given the linked list and an array arr[] of size N, the task is to reverse every arr[i] nodes of the list at a time (0 ⤠i < N). Note: If the number of nodes in the list is greater than the sum of array, then the remaining nodes will remain as it is. Examples: Input: head = 1->2->3->4-
8 min read
Javascript Program For Reversing A Linked List In Groups Of Given Size - Set 1 Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Example: Input: 1->2->3->4->5->6->7->8->NULL, K = 3 Output: 3->2->1->6->5->4->8->7->NULL Input: 1->2->3->4->5->6->7->8->NULL,
3 min read
Javascript Program For Reversing A Linked List In Groups Of Given Size- Set 2 Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Examples:Input: 1->2->3->4->5->6->7->8->NULL and k = 3 Output: 3->2->1->6->5->4->8->7->NULL. Input: 1->2->3->4->5->6->7->8->NU
3 min read