×

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

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree. Implementation /* creating a program that...

4 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.

Equal Sum

Find an element in array such that the sum of left array is equal to the sum of right array You have been given an array of numbers. You have to...

4 minutes read.

A Full Binary Tree with n Nodes

Implementation // Writing the implementation of the above approach in C++ #include <bits/stdc++.h> using namespace std; // We are creating a class that will create a node and its left and right children.  struct __nod...

12 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Polish Notation in Data Structures

Arithmetic Expression: An arithmetic expression is defined as several operands or data items combined using several operators. For example; a+b*(c-d) is an expression. Operands: Operands represent the data in an expression...

2 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.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Operations on 1D-Arrays

One Dimensional Array Operations Basic Methods The fundamental operations enabled by an array are listed below. Traverse prints each element of the array one by one.Insert a new element at the specified index.Delete...

8 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Bubble Sort vs Merge Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Merge Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Adding one to the number represented an array of digits

You have given one array, which consists of values which represent the different digits of a number. You have to add 1 to this number and store the result in...

3 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.