×

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List

In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such a way that all even numbers appear before all the odd numbers in the new linked list. We will also preserve the order of even and odd numbers.

Examples:

Input: 19 -> 13 -> 6 -> 10 -> 2 -> 7 -> 12 -> 1 -> 8 ->NULL

Output: 6 -> 10 -> 2 -> 12 -> 8 -> 19 -> 13 -> 7 -> 1 -> NULL

Note: If all numbers are even then do not change the list

Input: 2 -> 4 -> 6 ->NULL

Output: 2 -> 4 -> 6 -> NULL

Note:If all numbers are odd, then do not change the list

Input: 1 ->3 ->5 ->7 ->NULL

Output: 1 ->3 ->5 ->7 ->NULL

Method 1:

1) Firstly, we will move the pointer to the last node.

2) Then, we will move all the odd nodes to the end.

a) We will consider all odd nodes before the first even node and move them to the end.

b)Next, we will Change the head pointer to point to the first even node.

c) Then, we will consider all odd nodes after the first even node and move them to the end.

C program to segregate even and odd nodes in a Linked List by method 1

 #include<stdio.h>
 #include<stdlib.h>
 //The structure of the node
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // program to segregate even and odd nodes in a Linked List
 voidsegregateEvenOdd(struct node **head_ref)
 {
 struct node *end = *head_ref;
 struct node *prev = NULL;
 struct node *curr = *head_ref;
 while (end->next != NULL)
 end = end->next;
 struct node *new_end = end;
 while (curr->info %2 != 0 &&curr != end)
     {
 new_end->next = curr;
 curr = curr->next;
 new_end->next->next = NULL;
 new_end = new_end->next;
     }
 if (curr->info%2 == 0)
     {
         *head_ref = curr;
 while (curr != end)
         {
 if ( (curr->info)%2 == 0 )
             {
 prev = curr;
 curr = curr->next;
             }
 else
             {
 prev->next = curr->next;
 curr->next = NULL;
 new_end->next = curr;
 new_end = curr;
 curr = prev->next;
             }
         }
     }
 elseprev = curr;
 if (new_end!=end && (end->info)%2 != 0)
     {
 prev->next = end->next;
 end->next = NULL;
 new_end->next = end;
     }
 return;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d  ->  ", t -> info);
                         t = t -> next;
                         }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 add(19);
 add(13);
 add(6);
 add(10);
 add(2);
 add(7);
 add(12);
 add(1);
 add(8);
 printf("Linked List before:\n");
 traverse(start);
 segregateEvenOdd(&start);
 printf("Linked List after:\n");
 traverse(start);
 return 0;
 } 

Output:

Segregate even and odd nodes in a Linked List

Method 2:

This method will split the given linked list into two parts, one part containing all the even nodes and the other part containing all the odd nodes. Finally, we will link the odd node linked list after the even node linked list.

C program to segregate even and odd nodes in a Linked List by method 2

 #include<stdio.h>
 #include<stdlib.h>
 // The structure of the node
 struct node
 {
 int info;
 struct node * next;
 };
 struct node * start = NULL;
 // For inserting the elements in the linked list
 void add(int item)
 {
 struct node * t, * p;
 t = (struct node * )malloc( sizeof( struct node ));
 if(start == NULL)
 {
 start = t;
 start -> info = item;
 start -> next = NULL;
 return;
 }
 else
 {
 struct node * p = start;
 while(p -> next != NULL)
 {
 p = p -> next;
 }
 p -> next = t;
 p = p -> next;
 p -> info = item;
 p -> next = NULL;
 }
 }
 // program to segregate even and odd nodes in a Linked List
 voidsegregateEvenOdd(struct node **head_ref)
 {
 struct node *evenStart = NULL;
 struct node *evenEnd = NULL;
 struct node *oddStart = NULL;
 struct node *oddEnd = NULL;
 struct node *currNode = *head_ref;
 while(currNode != NULL){
 intval = currNode -> info;
 if(val % 2 == 0) {
 if(evenStart == NULL){
 evenStart = currNode;
 evenEnd = evenStart;
             }
 else{
 evenEnd -> next = currNode;
 evenEnd = evenEnd -> next;
             }
         }
 else{
 if(oddStart == NULL){
 oddStart = currNode;
 oddEnd = oddStart;
             }
 else{
 oddEnd -> next = currNode;
 oddEnd = oddEnd -> next;
             }
         }
 currNode = currNode -> next;
     }
 if(oddStart == NULL || evenStart == NULL){
 return;
     }
 evenEnd -> next = oddStart;
 oddEnd -> next = NULL;
     *head_ref = evenStart;
 }
 // To display the elements of the linked list
 void traverse(struct node * t)
 {
 if(t == NULL)
 {
             printf(" Linked list is empty\n");
                                     }
                                     while(t -> next != NULL)
                                     {
                         printf("%d  ->  ", t -> info);
                         t = t -> next;
                         }
                         printf("%d\n", t -> info);
 }
 // Driver Function
 int main()
 {
 add(3);
 add(5);
 add(9);
 add(11);
 add(13);
 add(15);
 add(17);
 printf("Linked List before:\n");
 traverse(start);
 segregateEvenOdd(&start);
 printf("Linked List after:\n");
 traverse(start);
 return 0;
 } 

Output:

Segregate even and odd nodes in a Linked List

Related Topics

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

8 minutes read.

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation...

3 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Application of 2D array - Sparse Matrix

2D Arrays Application - Sparse Matrix A matrix is a two-dimensional data item consisting of m rows and n columns, with a total of m x n values. A sparse matrix...

7 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Breadth First Search

Breadth First Search Breadth first search is a graph traversing algorithm. In this, we start traversing from the source node or any selected node and traverse the graph layer by layer....

6 minutes read.