×

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

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Box Stacking Problem

Stacking of boxes depending on their base You have been given n different boxes. These boxes will have different heights, widths, and depths. You have to stack all these boxes in...

4 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 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.

Delete the Middle element of the Linked List in C

Delete the Middle element of the Linked List in C This article has given a singly linked list and will delete the middle element of the given linked list. Example:  The given...

3 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

3 minutes read.

How to Start Learning DSA

All programmer experiences a point along the way where they wish they could approach a problem in a more effective manner. They finally learn about the terminology DSA while trying...

10 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Bookshop management system using file handling in C++

We see different software in every hospitals or library to manage their database. It is very important to store organization’s data. So we use this software. Now we are going...

5 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

What is Skewed Binary Tree

To understand the skewed binary tree, we must first understand the concept of a binary tree. A binary is generally the one in which every single node has two further...

3 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.