Open In App

Rearrange a linked list in to alternate first and last element

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. Rearrange the nodes in the list so that the newly formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ... You are required to do this in place without altering the nodes' values. 

Examples: 

Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 1 -> 5 -> 2 -> 4 -> 3
Explanation: Here n = 5, so the correct order is L0->L4->L1->L3->L2

Input: 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3
Explanation: Here n = 4, so the correct order is L0->L3->L1->L2

Refer to Rearrange a given linked list in-place for naive and in-place approaches. Here, deque approach is used.

Approach:

The idea is to use a deque (double-ended queue) to store all nodes of the linked list, then reconstruct the list by alternatively taking nodes from the front and back of the deque.

Step by step approach:

  1. Push all nodes of the original linked list into a deque.
  2. Create a dummy node to simplify the construction of the reordered list.
  3. Iterate until the deque is empty, alternatively popping from front and back.
  4. Connect nodes in the new order: front → back → front → back.
  5. Update the original list to the reordered version.
C++
// C++ code to rearrange a given linked list
#include <bits/stdc++.h>
using namespace std;

class Node {
  public:
    int data;
    Node *next;
    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to rearrange a given linked list
void reorderList(Node* head) {
    if (head == nullptr)
        return;
    
    // Store all nodes in a deque
    deque<Node*> dq;
    Node* curr = head;
    while (curr) {
        dq.push_back(curr);
        curr = curr->next;
    }
    
    // Create a dummy node for easy inserting
    Node* dummy = new Node(0);
    Node* tail = dummy;
    
    bool fromFront = true;
    
    while (!dq.empty()) {
        if (fromFront) {
            tail->next = dq.front();
            dq.pop_front();
        } 
        else {
            tail->next = dq.back();
            dq.pop_back();
        }
        tail = tail->next;
        fromFront = !fromFront;
    }
    
    // Next of tail should be NULL
    tail->next = nullptr;
    
    // Update the original list
    head = dummy->next;
}

int main() {
    
    // singly linked list 1->2->3->4->5
    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5); 
  	
    reorderList(head); 
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
    return 0;
}
Java
// C++ code to rearrange a given linked list

class Node {
    int data;
    Node next;
    Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {
    
    // Function to rearrange a given linked list
    static void reorderList(Node head) {
        if (head == null)
            return;
        
        // Store all nodes in a deque
        java.util.Deque<Node> dq = new java.util.ArrayDeque<>();
        Node curr = head;
        while (curr != null) {
            dq.addLast(curr);
            curr = curr.next;
        }
        
        // Create a dummy node for easy inserting
        Node dummy = new Node(0);
        Node tail = dummy;
        
        boolean fromFront = true;
        
        while (!dq.isEmpty()) {
            if (fromFront) {
                tail.next = dq.removeFirst();
            } 
            else {
                tail.next = dq.removeLast();
            }
            tail = tail.next;
            fromFront = !fromFront;
        }
        
        // Next of tail should be NULL
        tail.next = null;
        
        // Update the original list
        head = dummy.next;
    }

    public static void main(String[] args) {
        
        // singly linked list 1->2->3->4->5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5); 
        
        reorderList(head); 
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }
}
Python
# C++ code to rearrange a given linked list

from collections import deque

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to rearrange a given linked list
def reorderList(head):
    if head is None:
        return
    
    # Store all nodes in a deque
    dq = deque()
    curr = head
    while curr:
        dq.append(curr)
        curr = curr.next
    
    # Create a dummy node for easy inserting
    dummy = Node(0)
    tail = dummy
    
    fromFront = True
    
    while dq:
        if fromFront:
            tail.next = dq.popleft()
        else:
            tail.next = dq.pop()
        tail = tail.next
        fromFront = not fromFront
    
    # Next of tail should be NULL
    tail.next = None
    
    # Update the original list
    head = dummy.next

if __name__ == "__main__":
    
    # singly linked list 1->2->3->4->5
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)
    
    reorderList(head)
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()
C#
// C++ code to rearrange a given linked list

using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;
    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {
    
    // Function to rearrange a given linked list
    static void reorderList(Node head) {
        if (head == null)
            return;
        
        // Store all nodes in a deque
        LinkedList<Node> dq = new LinkedList<Node>();
        Node curr = head;
        while (curr != null) {
            dq.AddLast(curr);
            curr = curr.next;
        }
        
        // Create a dummy node for easy inserting
        Node dummy = new Node(0);
        Node tail = dummy;
        
        bool fromFront = true;
        
        while (dq.Count > 0) {
            if (fromFront) {
                tail.next = dq.First.Value;
                dq.RemoveFirst();
            } 
            else {
                tail.next = dq.Last.Value;
                dq.RemoveLast();
            }
            tail = tail.next;
            fromFront = !fromFront;
        }
        
        // Next of tail should be NULL
        tail.next = null;
        
        // Update the original list
        head = dummy.next;
    }

    static void Main() {
        
        // singly linked list 1->2->3->4->5
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5); 
        
        reorderList(head); 
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }
}
JavaScript
// C++ code to rearrange a given linked list

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function to rearrange a given linked list
function reorderList(head) {
    if (head == null)
        return;
    
    // Store all nodes in an array (used as deque)
    let dq = [];
    let curr = head;
    while (curr) {
        dq.push(curr);
        curr = curr.next;
    }
    
    // Create a dummy node for easy inserting
    let dummy = new Node(0);
    let tail = dummy;
    
    let fromFront = true;
    let i = 0, j = dq.length - 1;
    
    while (i <= j) {
        if (fromFront) {
            tail.next = dq[i++];  
        } 
        else {
            tail.next = dq[j--];   
        }
        tail = tail.next;
        fromFront = !fromFront;
    }
    
    // Next of tail should be NULL
    tail.next = null;
    
    // Update the original list
    head = dummy.next;
}

// singly linked list 1->2->3->4->5
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5); 

reorderList(head); 
let curr = head;
while (curr != null) {
    process.stdout.write(curr.data + " ");
    curr = curr.next;
}
console.log();

Output
1 5 2 4 3 

Time Complexity : O(n)
Auxiliary space: O(n), due to deque.


Next Article
Article Tags :
Practice Tags :

Similar Reads