C++ Program For Segregating Even And Odd Nodes In A Linked List
Last Updated :
22 Dec, 2022
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers the same.
Examples:
Input: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL
Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL
// If all numbers are even then do not change the list
Input: 8->12->10->NULL
Output: 8->12->10->NULL
// 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:
The idea is to get pointer to the last node of list. And then traverse the list starting from the head node and move the odd valued nodes from their current position to end of the list.
Thanks to blunderboy for suggesting this method.
Algorithm:
- Get pointer to the last node.
- Move all the odd nodes to the end.
- Consider all odd nodes before the first even node and move them to end.
- Change the head pointer to point to the first even node.
- Consider all odd nodes after the first even node and move them to the end.
Below is the implementation of the above approach:
C++
// C++ program to segregate even and
// odd nodes in a Linked List
#include <bits/stdc++.h>
using namespace std;
// A node of the singly linked list
class Node
{
public:
int data;
Node *next;
};
void segregateEvenOdd(Node **head_ref)
{
Node *end = *head_ref;
Node *prev = NULL;
Node *curr = *head_ref;
// Get pointer to the last node
while (end->next != NULL)
end = end->next;
Node *new_end = end;
/* Consider all odd nodes before
the first even node and move
then after end */
while (curr->data % 2 != 0 &&
curr != end)
{
new_end->next = curr;
curr = curr->next;
new_end->next->next = NULL;
new_end = new_end->next;
}
// 10->8->17->17->15
/* Do following steps only if
there is any even node */
if (curr->data%2 == 0)
{
/* Change the head pointer to
point to first even node */
*head_ref = curr;
/* Now current points to
the first even node */
while (curr != end)
{
if ( (curr->data) % 2 == 0 )
{
prev = curr;
curr = curr->next;
}
else
{
/* Break the link between
prev and current */
prev->next = curr->next;
// Make next of curr as NULL
curr->next = NULL;
// Move curr to end
new_end->next = curr;
// Make curr as new end of list
new_end = curr;
/* Update current pointer to
next of the moved node */
curr = prev->next;
}
}
}
/* We must have prev set before
executing lines following this
statement */
else prev = curr;
/* If there are more than 1 odd nodes
and end of original list is odd then
move this node to end to maintain
same order of odd numbers in modified
list */
if (new_end != end &&
(end->data) % 2 != 0)
{
prev->next = end->next;
end->next = NULL;
new_end->next = end;
}
return;
}
// UTILITY FUNCTIONS
/* Function to insert a node at
the beginning */
void push(Node** head_ref,
int new_data)
{
// Allocate node
Node* new_node = new Node();
// Put in the data
new_node->data = new_data;
// Link the old list off the
// new node
new_node->next = (*head_ref);
// Move the head to point to
// the new node
(*head_ref) = new_node;
}
// Function to print nodes in a
// given linked list
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data <<" ";
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty list
Node* head = NULL;
/* Let us create a sample
linked list as following
0->2->4->6->8->10->11 */
push(&head, 11);
push(&head, 10);
push(&head, 8);
push(&head, 6);
push(&head, 4);
push(&head, 2);
push(&head, 0);
cout << "Original Linked list ";
printList(head);
segregateEvenOdd(&head);
cout << "Modified Linked list ";
printList(head);
return 0;
}
// This code is contributed by rathbhupendra
OutputOriginal Linked list 0 2 4 6 8 10 11 Modified Linked list 0 2 4 6 8 10 11
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2:
The idea is to split the linked list into two: one containing all even nodes and other containing all odd nodes. And finally, attach the odd node linked list after the even node linked list.
To split the Linked List, traverse the original Linked List and move all odd nodes to a separate Linked List of all odd nodes. At the end of the loop, the original list will have all the even nodes and the odd node list will have all the odd nodes. To keep the ordering of all nodes the same, we must insert all the odd nodes at the end of the odd node list. And to do that in constant time, we must keep track of the last pointer in the odd node list.
C++
// CPP program to segregate even and
// odd nodes in a Linked List
#include <stdio.h>
#include <stdlib.h>
// A node of the singly linked list
struct Node
{
int data;
struct Node *next;
};
// Function to segregate even and
// odd nodes.
void segregateEvenOdd(struct Node **head_ref)
{
// Starting node of list having
// even values.
Node *evenStart = NULL;
// Ending node of even values list.
Node *evenEnd = NULL;
// Starting node of odd values list.
Node *oddStart = NULL;
// Ending node of odd values list.
Node *oddEnd = NULL;
// Node to traverse the list.
Node *currNode = *head_ref;
while(currNode != NULL)
{
int val = currNode -> data;
// If current value is even, add
// it to even values list.
if(val % 2 == 0)
{
if(evenStart == NULL)
{
evenStart = currNode;
evenEnd = evenStart;
}
else
{
evenEnd -> next = currNode;
evenEnd = evenEnd -> next;
}
}
// If current value is odd, add
// it to odd values list.
else
{
if(oddStart == NULL)
{
oddStart = currNode;
oddEnd = oddStart;
}
else
{
oddEnd -> next = currNode;
oddEnd = oddEnd -> next;
}
}
// Move head pointer one step in
// forward direction
currNode = currNode -> next;
}
// If either odd list or even list
// is empty, no change is required
// as all elements are either even
// or odd.
if(oddStart == NULL ||
evenStart == NULL)
{
return;
}
// Add odd list after even list.
evenEnd -> next = oddStart;
oddEnd -> next = NULL;
// Modify head pointer to
// starting of even list.
*head_ref = evenStart;
}
// UTILITY FUNCTIONS
/* Function to insert a node at
the beginning */
void push(struct Node** head_ref,
int new_data)
{
// Allocate node
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
// Put in the data
new_node->data = new_data;
// Link the old list off the
// new node
new_node->next = (*head_ref);
// Move the head to point to the
// new node
(*head_ref) = new_node;
}
/* Function to print nodes in a
given linked list */
void printList(struct Node *node)
{
while (node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
// Driver code
int main()
{
// Start with the empty list
struct Node* head = NULL;
/* Let us create a sample
linked list as following
0->1->4->6->9->10->11 */
push(&head, 11);
push(&head, 10);
push(&head, 9);
push(&head, 6);
push(&head, 4);
push(&head, 1);
push(&head, 0);
printf("Original Linked list ");
printList(head);
segregateEvenOdd(&head);
printf("Modified Linked list ");
printList(head);
return 0;
}
// This code is contributed by NIKHIL JINDAL.
OutputOriginal Linked list 0 1 4 6 9 10 11 Modified Linked list 0 4 6 10 1 9 11
Time complexity: O(n)
Auxiliary space: O(1) because using constant space
Please refer complete article on Segregate even and odd nodes in a Linked List for more details!
Similar Reads
C++ Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functi
4 min read
C++ Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where
8 min read
C++ Program for Deleting a Node in a Linked List
Write a C++ program to delete a node from the given link list.ExamplesInput: Linked List: 10 -> 20 -> 30 -> 40 -> 50, Position to delete: 3Output: 10 -> 20 -> 40 -> 50Explanation: The node at position 3 is removed. The list then connects node 20 directly to node 40.Input: Linked
6 min read
C++ Program For Removing Every K-th Node Of The Linked List
Given a singly linked list, Your task is to remove every K-th node of the linked list. Assume that K is always less than or equal to length of Linked List.Examples : Input: 1->2->3->4->5->6->7->8 k = 3 Output: 1->2->4->5->7->8 As 3 is the k-th node after its deletion list would be 1->2->4->5->6->7->
3 min read
C++ Program For Reversing Alternate K Nodes In A Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6-
6 min read
C++ Program For Deleting A Node In A Doubly Linked List
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
4 min read
C++ Program For Sorting A Linked List Of 0s, 1s And 2s
Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL So
3 min read
C++ Program For Writing A Function To Get Nth Node In A Linked List
Write a C++ Program to GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before m
4 min read
C++ Program For Writing A Function To Delete A Linked List
Algorithm For C++:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C++ // C++ program to delete a linked list #include <bits/stdc++.h> using namespace std
2 min read
C++ Program For Detecting Loop In A Linked List
Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. The following are different ways of doing this. Solution 1: Hashing Approach: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reach
11 min read