Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Rearrange a linked list such that all even and odd positioned nodes are together

Last Updated on November 25, 2022 by Prepbytes

A linked list is a linear data structure. In the linked list elements are not stored continuously but randomly. It is a vital topic from the placement point of view, and there are several problems related to it. In this blog, we will learn to rearrange a linked list such that all even and odd positioned nodes are together

## How to rearrange a linked list such that all even and odd positioned nodes are together

In this problem, we will be given a linked list, and we need to rearrange the nodes such that the nodes present at odd positions and the nodes present at even positions are together.

To understand this problem statement, let us take examples.

If the given linked list is:

then according to the problem statement:

• Starting the counting from 1, the nodes at odd positions are 3,18, and 5.
• Nodes at even positions are 1 and 12.
• So, after rearrangement, the resultant list will be:

Let us take another example:
If the linked list is 4→1→10→42→5→NULL.

• Starting the counting from 1, the nodes at odd positions are 4,10, and 5.
• Nodes at even positions are 1 and 42.
• So, after rearrangement, the resultant list will be 4→10→5→1→42→NULL.

Now, I think the problem statement is clear, so let’s see how we can approach it. Any ideas?

• If not, it’s okay; we will see in the next section how we can approach it.

Let’s move to the approach section.

## Approach of rearrange a linked list such that all even and odd positioned nodes are together

• We will use two pointers, where at first, we will initialize these pointers with the address of the first and the second node of the linked list.
• Now, we will iterate the list from the first node to the last node.
• While iterating, we will connect the node pointed by each pointer to the node next to the adjacent node in its right.
• This will ensure that all odd and even positioned nodes are with each other, respectively.
• At last, we need to connect the tail of the odd list with the head of the even list.
• Finally, after all the above steps, we will have our rearranged linked list with all the even and the odd-positioned nodes together.

The approach is discussed in more depth in the algorithm section.

## Algorithm of rearrange a linked list such that all even and odd positioned nodes are together

1) We will return NULL if the head is NULL, i.e., the input list is empty.
2) Initialize two pointers odd and even with the first and the second node of the list, respectively.
3) Initialize a pointer evenHead with the second node.
4) Run an infinite while loop and inside it:

• If any one of odd, even, or even→next is NULL (i.e., we have reached the end of the list, so we will connect the last node of odd list to the first node of the even list), then attach the tail of odd to the head of even and break from the loop.
• Connect odd to the node next to even and update odd with this node.
• If the node next to odd is NULL (i.e., no node after the current odd node), then update the next of even as NULL and attach the tail of odd to the head of even and break from the loop.
• Connect even to the node next to odd and update even with this node.
5) Return head at last from the function.

## Code Implementation of rearrange a linked list such that all even and odd positioned nodes are together

```#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node* next;
};

// A utility function to create a new node
struct Node* newNode(int key)
{
struct Node *temp = (struct Node *) malloc(sizeof(struct Node));
temp->data = key;
temp->next = NULL;
return temp;
}

// Rearranges given linked list such that all even
// positioned nodes are before odd positioned.
{
// Corner case
return NULL;

// Initialize first nodes of even and
// odd lists

// Remember the first node of even list so
// that we can connect the even list at the
// end of odd list.
struct Node *evenFirst = even;

while (1)
{
// If there are no more nodes, then connect
// first node of even list to the last node
// of odd list
if (!odd || !even || !(even->next))
{
odd->next = evenFirst;
break;
}

// Connecting odd nodes
odd->next = even->next;
odd = even->next;

// If there are NO more even nodes after
// current odd.
if (odd->next == NULL)
{
even->next = NULL;
odd->next = evenFirst;
break;
}

// Connecting even nodes
even->next = odd->next;
even = odd->next;
}

}

// A utility function to print a linked list
void printlist(struct Node * node)
{
while (node != NULL)
{
printf("%d->",node->data);
node = node->next;
}
printf("NULL\n");
}

// Driver code
int main(void)
{

return 0;
}
```
```#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int x){
data = x;
next = NULL;
}
};

// Using this function we will print the linked list
{
return;

{
}
}

// Function to rearrange the linked list
{
// Empty list condition
return NULL;

// first node of even list

while (1)
{
// If we have reached end of the list
// then, connect last node of odd list
// to the first node of even list
if (!odd || !even || !(even->next))
{
break;
}

odd->next = even->next;
odd = even->next;

// No nodes after current odd node
if (odd->next == NULL)
{
even->next = NULL;
break;
}

even->next = odd->next;
even = odd->next;
}

}

int main(void){
cout<<"Original linked list without rearrangement: "<<endl;
printList(tmp);
return 0;
}

```
```class Rearrange
{
static class Node
{
int data;
Node next;
}
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
/* Rearranges given linked list such that all even positioned
{
// Corner case
return null;

// Initialize first nodes of even and odd lists

/* Remember the first node of even list so
that we can connect the even list at the end of odd list.*/
Node evenFirst = even;

while (1 == 1)
{
/* If there are no more nodes,
then connect first node of even
list to the last node of odd list*/
if (odd == null || even == null ||(even.next) == null)
{
odd.next = evenFirst;
break;
}
// Connecting odd nodes
odd.next = even.next;
odd = even.next;
// If there are NO more even nodes after current odd.
if (odd.next == null)
{
even.next = null;
odd.next = evenFirst;
break;
}
// Connecting even nodes
even.next = odd.next;
even = odd.next;
}
}
static void printlist(Node node)
{
while (node != null)
{
System.out.print(node.data + "->");
node = node.next;
}
System.out.println("NULL") ;
}
// Driver code
public static void main(String[] args)
{

}
}
```
```class Node:
def __init__(self, d):
self.data = d
self.next = None

def __init__(self):

def newNode(self, key):
temp = Node(key)
self.next = None
return temp

return None

evenFirst = even

while (1 == 1):

if (odd == None or even == None or
(even.next) == None):
odd.next = evenFirst
break

odd.next = even.next
odd = even.next

if (odd.next == None):
even.next = None
odd.next = evenFirst
break

even.next = odd.next
even = odd.next

def printlist(self, node):
while (node != None):
print(node.data, end = "")
print("->", end = "")
node = node.next
print ("NULL")

def push(self, new_data):
new_node = Node(new_data)

ll.push(5)
ll.push(12)
ll.push(18)
ll.push(1)
ll.push(3)

ll.printlist(start)
```

Output
3,1,18,12,5
3,18,5,1,12

Time Complexity of rearrange a linked list such that all even and odd positioned nodes are together: O(n), where n is the total number of nodes in the list.

So, in this blog, we have tried to explain how we can rearrange a linked list such that all even and odd positioned nodes are together most optimally. Practicing a bunch of questions is not enough in this competitive world. So go check out where you stand among your peers by taking our Linked List.and see which areas need improvement

## FAQs

**1. What is the key difference between a singly linked list and a doubly-linked list?**
A singly-linked list is unidirectional, which means that the node of a singly-linked list contains the pointer to its next node only. In contrast, a doubly-linked list is bidirectional, and its node contains the pointer to its next and previous nodes.

**2. How do you sort a linked list?**
Below is a simple insertion sort algorithm for a linked list.
– Create an empty sorted (or result) list.
– Traverse the given list, and do the following for every node.
– Insert the current node in a sorted way in a sorted or result list.
– Change the head of the given linked list to the head of the sorted (or result) list.

**3. Which of the following method is used for sorting in merge sort?**
The divide and conquer technique is used for merge sort.