×

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

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Delete nodes from the linked list which have a greater value on the right side

Delete nodes from the linked list which have a greater value on the right side In this problem, we have given a singly linked list, and we need to remove all...

3 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

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

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Binary Tree Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

4 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Recaman’s Sequence

Recamán's succession repeat connection in arithmetic and software engineering. Since its components are obviously connected with the past components, they are as often as possible characterized utilizing recursion. It takes its...

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

Understanding Data Processing

Introduction Data In our everyday lives, any task that we perform online is related to data. Millions of pieces of data are produced every second across the globe. Data production is largely...

4 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

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

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.

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.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.