×

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

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

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

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Spanning Tree

Spanning Tree: The spanning tree is a subset of the graph. It is a non-cyclic graph. If any node in the spanning tree is truncated, the entire graph fails. There are...

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

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

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.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

Bubble Sort vs Selection Sort

In this article, we will discuss the basic differences between these two sorting algorithms. Let us have a quick overview of what these sorting algorithms are? And what are the...

6 minutes read.

Counts the number of times a given element occurs in a Linked List

Counts the number of times a given element occurs in a Linked List This article will explain how we can count the occurrences of a particular element in a list. Here,...

3 minutes read.

Given a Binary Tree Print the Shortest Path

Implementation // Writing a program in C++ to find the shortest between the nodes i and j.  #include <bits/stdc++.h> using namespace std; // the given function will print the path between nodes i and...

7 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

Berkley’s Algorithm

Berkley’s Algorithm is mainly used in clock synchronization system. It is used in distributed systems. To implement this algorithm, we have to think that the network has no accurate time...

4 minutes read.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

4 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

Delete N nodes after M nodes of a linked list

Delete N nodes after M nodes of a linked list In this problem, we have given a linked list and two integers M and N. We need to traverse the linked...

3 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

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.