×

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

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.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Why is Binary Heap Preferred over BST for Priority Queue

A priority queue is a linear and ordered collection of elements in which each element has an attribute named priority and the priority attribute decides the order in which elements...

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

Print kth least significant bit number

You have given a number and you have to find out the kth least significant bit of this number. K will be given to you.  The bit will be from...

3 minutes read.

Operations on 1D-Arrays

One Dimensional Array Operations Basic Methods The fundamental operations enabled by an array are listed below. Traverse prints each element of the array one by one.Insert a new element at the specified index.Delete...

8 minutes read.

Linear Queue VS Circular Queue

What is Queue? A queue is one of the important linear data structures extensively used in various computer applications. It is based on the FIFO (First In First Out) principle. It...

9 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because...

6 minutes read.

Difference Between Linear and Non Linear Data Structures

Data Structure A data structure is a data object together with the relationships between the instances and the individual elements that compose an instance. These relationships are defined by the operations...

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

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Diameter of a Binary Tree

Implementation We will now witness the implementation of the diameter of a binary tree. // Creating a recursive and challenging C program that will help us determine the diameter of a binary...

4 minutes read.