×

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

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

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

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree. Implementation #include <bits/stdc++.h> using namespace std; /* A binary tree node...

4 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

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.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

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

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

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

3 minutes read.

Function to Delete a Leaf Node from a Binary Tree

Implementation // We are writing a C++ code to eliminate all the leaves from the given value.  #include <bits/stdc++.h> using namespace std; // creating a new binary tree node struct __nod { int record; struct __nod *Lft,...

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

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Trie data structure

Trie data structure The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure...

5 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

What is the B+ Tree in Data Structures?

We all know that the B+ tree in data structures is nothing but just an extended version of the B tree. It allows the smooth working of all the operations...

7 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.