×

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element

This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here, we have given a singly linked list, and we need to arrange the given linked list alternately, like the first element, then the last element, and so on.

Example: -

                             Input: 2  ->  4  ->  6  ->  8  ->  10  ->  12  ->  14  ->  16

                                    Output: 2  ->  16  ->  4  ->  14  ->  6  ->  12  ->  8  ->  10

                                    Input: 1  ->  2  ->  3  ->  4  ->  5

                                    Output: 1  ->  5  ->  2  ->  4  ->  3

Method:

We can do this by using the following steps:

  • Firstly, we will divide the given linked list into two parts.
  • Then, we will reverse the second part of the linked list.
  • After this, we will merge the first part and second part of the linked list in an alternate fashion.

Java program to rearrange a linked list into alternate fashion first and last element

 import java.util.*;
 class Node
 {
             int data;
             Node next;
             Node(int d)
             {
                         data = d;
                         next = null; 
             }
 }
 public class RearrangeLinkedList
 {
 Node head, second;
 /* Function to print linked list */
     void traverse(Node head)
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data+" ");
            temp = temp.next;
         } 
         System.out.println();
     }
     /* Function for reverse the linked list */
     Node reverse(Node temp)
     {
         Node prev = null;
         Node current = temp;
         Node next;
         while (current != null) {
             next = current.next;
             current.next = prev;
             prev = current;
             current = next;
         }
         return prev;
     }
 // Function for find the middle node of the linked list
    public static Node findMiddle(Node head)
     {
         Node prev = null;
         Node slow = head, fast = head;
         // find the middle pointer
         while (fast != null && fast.next != null)
         {
             prev = slow;
             slow = slow.next;
             fast = fast.next.next;
         }
         // for odd nodes, fix middle
         if (fast != null && fast.next == null)
         {
             prev = slow;
             slow = slow.next;
         }
         // make next of previous node null
         prev.next = null;
         // return middle node
         return slow;
     }
 // Function for rearranging the linked list in an alternate fashion
     public void rearrange(Node head)
     {
             if (head == null)       
                         return;
             Node middle = findMiddle(head);
             second =  reverse(middle);
             head=merge(head, second);
      }
 // Function for merge the first and second halves of the linked list
     public Node merge(Node first, Node second)
     {
     if (first == null) {
             return second;
         }
         if (second == null) {
             return first;
         }
         Node recursion = merge(first.next, second.next);
         Node res = first;      
         first.next = second;           
         second.next = recursion;        
         return res;
 }
 // Driver Function    
 public static void main(String args[])
             {
                         Scanner sc = new Scanner(System.in);
                         System.out.println("Enter the total no of elements in linked list: ");
                                     int n = sc.nextInt();
                         System.out.println("Enter the elements of linked list: ");
                                     int a1 = sc.nextInt();
                                     RearrangeLinkedList ob = new RearrangeLinkedList();
                                     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;
                                     }
                                     ob.rearrange(head);
                                     System.out.print("Rearranged List:-");
                                     ob.traverse(head);
             }
 } 

Output:

Rearrange a linked list into alternate

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


Related Topics

What is a Spanning Tree 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,...

5 minutes read.

Program to calculate the area of the circumcircle of an equilateral triangle

You have given one value which represents the side of the equilateral triangle. You have to find out the area of the circumcircle. Let’s take an example - For the above...

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

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Counting Sort

Counting Sort: Counting sort is a sorting algorithm that is used to sort the elements of the array within a specific range. It counts the same element number of the...

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

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

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

Rotate a Singly Linked List

Rotate a Singly Linked List This article will explain how we can rotate the singly linked list. Here we have given a singly linked list, and we need to rotate this...

4 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

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

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

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

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

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

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.