VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-a-given-linked-list-in-place/

⇱ Rearrange a linked list in alternat first and last - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange a linked list in alternat first and last

Last Updated : 30 Mar, 2026

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
Output: 1 -> 4 -> 2 -> 3
Explanation: Here n = 4, so the correct order is L0->L3->L1->L2

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

[Naive Approach] Using two nested loops- O(n^2) Time and O(1) Space

The idea is to start traversing from head node. For each node, perform the following operations:

  • Traverse the list to find the last node.
  • Disconnect the last node from the list.
  • Place the removed last node after the current node.
  • Update current to its next node.

[Efficient Approach] By Reversing Second Half - O(n) Time and O(1) Space

  • Find the middle of the linked list using the fast and slow pointer method. This involves moving one pointer twice as fast as the other so that when the faster pointer reaches the end, the slower pointer will be at the middle.
  • Reverse the second half of the list starting just after the middle node and split them in two parts.
  • Merge the two halves together by alternating nodes from the first half with nodes from the reversed second half.

Output
1 5 2 4 3 
Comment
Article Tags: