×

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

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.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Union and Intersection of two Linked Lists

Union and Intersection of two Linked Lists This article explains how we can do the union and intersection of two linked lists. In this problem, we have given two linked lists...

3 minutes read.

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.

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.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

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

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 Search

Binary Search: When there is a large data structure, the linear search takes a lot of time to search the element. The binary search was developed to overcome the lack...

7 minutes read.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Introduction to 2D-Arrays

Two Dimensional Array Technical Definitions An array of arrays is a common definition for a two-dimensional array. A matrix is another name for a two-dimensional array. A matrix looks like a table...

3 minutes read.