# How to Segregate a given Linked List in C++

C++Server Side ProgrammingProgramming

A Linked List is a linear data structure in which each node has two blocks such that one block contains the value or data of the node and the other block contains the address of the next field.

Let us assume that we have a linked list such that each node contains the data and a pointer which is pointing to the next node of the linked list. The task is to segregate the given Linked List. Segregating the linked list means we have to separate the odd indexed nodes and even index nodes in the list.

## Approach to Solve this Problem

To segregate a given linked list, we will introduce three pointers for the odd index, the even index, and the value at the even index, respectively. After that, we will iterate over the whole linked list and initialize the pointer with some value.

In the linked list, the indexing starts from '1', thus for any particular string, the first node of the list will always be treated as an odd indexed node. However, the next node is treated as an even indexed node.

• Take a linked list with data and pointer to the next node.
• A function segregateList(listnode *head) takes the pointer to the head node and returns the segregated linked list as the output.
• Initialize three pointers oddIndex, evenIndex and evenHead which are currently pointing to the head of the list.
• Iterate over the whole linked list and initialize the next pointer of oddIndex with the next pointer of evenIndex.
• Now iterate over the whole list and initialize the next pointer of evenIndex with the next pointer of oddIndex.

## Example

Live Demo

#include <iostream>
using namespace std;
class node {
public:
int data;
node * next;
node(int d) {
data = d;
next = NULL;
}
};
node * segregateList(node * head) {
return NULL;
}
node * evenIndex = head -> next;
while (evenIndex != NULL and evenIndex -> next != NULL) {
oddIndex -> next = evenIndex -> next;
oddIndex = oddIndex -> next;
evenIndex -> next = oddIndex -> next;
evenIndex = evenIndex -> next;
}
}
void insertAtNode(node * & head, int data) {
node * n = new node(data);
}
cout << head -> data << "->";
}
}
int main() {
// It could be possible that the head node contains NULL Value.
cout << endl;
}
2->3->5->1->8->