# Javascript Program For Rearranging A Given Linked List In-Place

• Last Updated : 15 Jun, 2022

Given a singly linked list L0 -> L1 -> … -> Ln-1 -> Ln. Rearrange the nodes in the list so that the new 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

Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 1 -> 5 -> 2 -> 4 -> 3```

Simple Solution:

```1) Initialize current node as head.
2) While next of current node is not null, do following
a) Find the last node, remove it from the end and insert it as next
of the current node.
b) Move current to next to next of current```

The time complexity of the above simple solution is O(n2) where n is the number of nodes in the linked list.

Better Solution:
1) Copy contents of the given linked list to a vector.
2) Rearrange the given vector by swapping nodes from both ends.
3) Copy the modified vector back to the linked list.
Implementation of this approach: https://ide.geeksforgeeks.org/1eGSEy
Thanks to Arushi Dhamija for suggesting this approach.

Efficient Solution:

```1) Find the middle point using tortoise and hare method.
2) Split the linked list into two halves using found middle point in step 1.
3) Reverse the second half.
4) Do alternate merge of first and second halves.```

The Time Complexity of this solution is O(n).

Below is the implementation of this method.

## Javascript

 ``

Output:

```1 -> 2 -> 3 -> 4 -> 5
1 -> 5 -> 2 -> 4 -> 3```

Time Complexity: O(n)
Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting the above approach.

Another approach:
2. Compare their data and swap.
After that, a new linked list is formed.

Below is the implementation:

## Javascript

 ``

Output:

`6 9 3 8 7`

Time Complexity : O(n)
Auxiliary Space : O(1)
Thanks to Aditya for suggesting this approach.

Another Approach: (Using recursion)

1. Hold a pointer to the head node and go till the last node using recursion
2. Once the last node is reached, start swapping the last node to the next of head node
3. Move the head pointer to the next node
4. Repeat this until the head and the last node meet or come adjacent to each other
5. Once the Stop condition met, we need to discard the left nodes to fix the loop created in the list while swapping nodes.

## Javascript

 ``

Output:

```1 ->2 ->3 ->4 ->5
1 ->5 ->2 ->4 ->3```

Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(n), due to recursive call stack where n represents the length of the given linked list.

Please refer complete article on Rearrange a given linked list in-place. for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :