×

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

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Splay Tree

Splay Tree A splay tree is a self-balanced or self-adjusted binary search tree. We can say, Splay Tree is used in some cases where some elements or data are accessed more...

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.

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

2 minutes read.

What is a full Binary Tree?

A full binary tree is considered to be a special kind of binary tree in which every single node or leaf node present either contains two children or no children...

4 minutes read.

Tree in Data Structure

Tree A tree is a non-linear data structure by which hierarchical data is displayed. As we know that there are many trees in the forest, similarly the data structure also contains...

3 minutes read.

Top view of binary tree

We know that a binary tree is a kind of tree that helps us organize our tree and that it is a kind of non-linear info structure that at least...

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

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.

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.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

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

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.

Heap Sort vs Merge Sort

In this article, we are going to discuss the Heap Sort, Merge sort and the difference between them. What is Heap Sort? Heap – A heap is an abstract data type categorised...

7 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

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