×

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size

This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list and we need to reverse every k nodes of the given linked list.

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, K = 5

Output: 5 -> 4 -> 3 -> 2 -> 1 -> 8 -> 7 -> 6 -> NULL

Algorithm:

  • Firstly, we will count the total number of nodes present in the given linked list.
  • Then, we will try to find the total number of reversal is required with the help of the total number of nodes divides by the value of k.
  • After this, we will apply the algorithm to reverse the singly linked list and return the head or starting pointer of the resultant linked list.

Source code to reverse the linked list in group size using Java

 import java.util.*;
 import java.lang.*;
 class Node
 {
     int data;
     Node next;
     Node(int key)
     {
         data = key;
         next = null;
     }
 }
 public class Main
 {
     public static void main (String[] args) {
         Scanner sc  =  new Scanner(System.in);
             System.out.println("Enter the total no of elements for linked list:");
             int n = sc.nextInt();
             System.out.println("Enter the elements for linked list:");
             int a1 = sc.nextInt();
             Node head = new Node(a1);
             Node tail = head;
             for(int i = 1; i < n; i++)
             {
                 int a  =  sc.nextInt();
                 tail.next  =  new Node(a);
                 tail  = tail.next;
             }
             System.out.println("Enter the value of k:");
             int k = sc.nextInt();
             ReverseInSize  ob = new ReverseInSize ();
             Node res = ob.reverse(head, k);
             printList(res);
             System.out.println();
     }
     public static void printList(Node node)
     {
             System.out.println("The resultant linked list is:");
         while(node != null)
         {
             System.out.print(node.data + " ");
             node = node.next;
         }
     }
 }
 //Driver Code Ends
 class ReverseInSize
 {
 // For reverse the linked list in groups of a given size
     public static Node reverse(Node head, int k)
     {
         Node temp = head;
         Node resultant = null;
         int count = 0;
        // For counting the total no of nodes present in the given linked list
         while(temp != null)
         {
             count++;
             temp = temp.next;
         }
         if(count%k == 0)
         {
             count = count/k;
         }
         else
             count = (count/k)+1;
         temp = head;
         while(count-- > 0)
         {
             int c = k;
             Node next = null;
             Node pre = null;
             Node curr = head;
             while(c-- > 0 && head != null)
                 head = head.next;
             c = k;
 // For reverse the linked list
             while(c-- > 0 && curr != null)
             {
                 next = curr.next;
                 curr.next = pre;
                 pre = curr;
                 curr = next;             
             }
             c = k;
             if(resultant == null)
                 resultant = pre;
             else
             {
                 Node tt = resultant;
                 while(tt.next != null)
                 {
                     tt = tt.next;
                 }
                 tt.next = pre;
             }
         }
         return resultant;
     }
 } 

Output: -

Reverse a Linked List in groups of given size

Complexity Analysis:

Time Complexity: The time complexity of this method is O(n).


Related Topics

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation...

3 minutes read.

Linear Queue Data Structure in C

Data Structure There are many ways to store data in programming, that Queue has features that make it all the more special. We all know that data structure is a way...

9 minutes read.

What is the difference between Tree and Graph

We usually use a diverse range of data structure to store our data and information. To store them in a more sequential manner and to access them easily, we use...

4 minutes read.

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Bubble Sort vs Heap Sort

In this article, we are going to compare the two most common sorting techniques, Bubble Sort and Heap sort. Before discussing their differences, let us first discuss the idea of...

7 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Linked List Data Structure

Linked list in DS: The linked list is a non-primitive and linear data structure. It is a list of a particular type of data element that is connected to each...

3 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Given a Binary Tree, find its Minimum Depth

Implementation // Creating a C++ program or implementation to search and explore the minimum depth of a given binary tree.  #include<bits/stdc++.h> using namespace std; // Creating a new binary tree node struct __nod { int record; struct __nod*...

5 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.