Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers.
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 Explanation: In the output list, we have all the even nodes first (in the same order as input list, then all the odd nodes of the list (in the same order as input list).
Input: 8->12->10->5->4->1->6->NULL Output: 8->12->10->4->6->5->1->NULL Explanation: We do not change the list as all the numbers are even.
Move Even and Append Remaining - O(n) Time and O(1) Space
1. Create an empty result list 2. Traverse the input list and move all even value nodes from the original list to the result list. If our original list was 17->15->8->12->10->5->4->1->7->6. Then after this step, we get original list as 17->15->5->1->7 and result list as 8->12->10->4->6 3. Append the remaining original list to the end of res and return result
C++
#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*next;Node(intx){data=x;next=nullptr;}};Node*segregateEvenOdd(Node*head){// Result list to hold even nodesNode*resStart=nullptr;Node*resEnd=nullptr;// Pointers for the original listNode*curr=head;Node*prev=nullptr;// Move all even nodes from original// to resultwhile(curr!=nullptr){// If current node is evenif(curr->data%2==0){// Remove the current even node // from the original listif(prev!=nullptr){prev->next=curr->next;}else{// If the even node is at the head head=curr->next;}// Add the current even node to the result listif(resStart==nullptr){resStart=curr;resEnd=resStart;}else{resEnd->next=curr;resEnd=resEnd->next;}curr=curr->next;}// If the node is odd, just move to the nextelse{prev=curr;curr=curr->next;}}// If there are no even nodes, return// the original listif(resStart==nullptr)returnhead;// Append the remaining original list// (odd nodes) to the result listresEnd->next=head;// Return the result list (starting with even nodes)returnresStart;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}}intmain(){// Let us create a sample linked list as following// 0->1->4->6->9->10->11Node*head=newNode(0);head->next=newNode(1);head->next->next=newNode(4);head->next->next->next=newNode(6);head->next->next->next->next=newNode(9);head->next->next->next->next->next=newNode(10);head->next->next->next->next->next->next=newNode(11);cout<<"Original Linked list: ";printList(head);head=segregateEvenOdd(head);cout<<"\nModified Linked list: ";printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to create a new nodestructNode*newNode(intx){structNode*temp=(structNode*)malloc(sizeof(structNode));temp->data=x;temp->next=NULL;returntemp;}// Function to segregate even and odd nodes // and return the head of the new liststructNode*segregateEvenOdd(structNode*head){// Result list to hold even nodesstructNode*resStart=NULL;structNode*resEnd=NULL;// Pointers for the original liststructNode*curr=head;structNode*prev=NULL;// Move all even nodes from original to resultwhile(curr!=NULL){// If current node is evenif(curr->data%2==0){// Remove the current even node// from the original listif(prev!=NULL){prev->next=curr->next;}else{// If the even node is at the headhead=curr->next;}// Add the current even node to the result listif(resStart==NULL){resStart=curr;resEnd=resStart;}else{resEnd->next=curr;resEnd=resEnd->next;}curr=curr->next;}else{// If the node is odd, just move to the nextprev=curr;curr=curr->next;}}// If there are no even nodes, return the original listif(resStart==NULL){returnhead;}// Append the remaining original list// (odd nodes) to the result listresEnd->next=head;// Return the result list (starting with even nodes)returnresStart;}// Function to print the linked listvoidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}intmain(){// Create a sample linked list: 0->1->4->6->9->10->11structNode*head=newNode(0);head->next=newNode(1);head->next->next=newNode(4);head->next->next->next=newNode(6);head->next->next->next->next=newNode(9);head->next->next->next->next->next=newNode(10);head->next->next->next->next->next->next=newNode(11);printf("Original Linked list: ");printList(head);head=segregateEvenOdd(head);printf("Modified Linked list: ");printList(head);return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}publicclassGfG{// Function to segregate even and odd nodes // and return the head of the new list.publicstaticNodesegregateEvenOdd(Nodehead){// Result list to hold even nodesNoderesStart=null;NoderesEnd=null;// Pointers for the original listNodecurr=head;Nodeprev=null;// Move all even nodes from original to resultwhile(curr!=null){// If current node is evenif(curr.data%2==0){// Remove the current even node from the original listif(prev!=null){prev.next=curr.next;}else{// If the even node is at the headhead=curr.next;}// Add the current even node to the result listif(resStart==null){resStart=curr;resEnd=resStart;}else{resEnd.next=curr;resEnd=resEnd.next;}// Move to the next nodecurr=curr.next;}else{// If the node is odd, just move to the nextprev=curr;curr=curr.next;}}// If there are no even nodes, return the original listif(resStart==null){returnhead;}// Append the remaining original list// (odd nodes) to the result listresEnd.next=head;// Return the result list (starting with even nodes)returnresStart;}// Function to print the linked listpublicstaticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}}publicstaticvoidmain(String[]args){// Let us create a sample linked list as following// 0->1->4->6->9->10->11Nodehead=newNode(0);head.next=newNode(1);head.next.next=newNode(4);head.next.next.next=newNode(6);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);head.next.next.next.next.next.next=newNode(11);System.out.print("Original Linked list: ");printList(head);head=segregateEvenOdd(head);System.out.print("\nModified Linked list: ");printList(head);}}
Python
classNode:def__init__(self,data):self.data=dataself.next=None# Function to segregate even and odd nodes # and return the head of the new list.defsegregateEvenOdd(head):# Result list to hold even nodesresStart=NoneresEnd=None# Pointers for the original listcurr=headprev=None# Move all even nodes from original to resultwhilecurrisnotNone:# If current node is evenifcurr.data%2==0:# Remove the current even node from the original listifprevisnotNone:prev.next=curr.nextelse:# If the even node is at the headhead=curr.next# Add the current even node to the result listifresStartisNone:resStart=currresEnd=resStartelse:resEnd.next=currresEnd=resEnd.nextcurr=curr.nextelse:# If the node is odd, just move to the nextprev=currcurr=curr.next# If there are no even nodes, return the original listifresStartisNone:returnhead# Append the remaining original list # (odd nodes) to the result listresEnd.next=head# Return the result list (starting with even nodes)returnresStart# Function to print the linked listdefprintList(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a sample linked list: 0->1->4->6->9->10->11head=Node(0)head.next=Node(1)head.next.next=Node(4)head.next.next.next=Node(6)head.next.next.next.next=Node(9)head.next.next.next.next.next=Node(10)head.next.next.next.next.next.next=Node(11)print("Original Linked list: ",end="")printList(head)head=segregateEvenOdd(head)print("Modified Linked list: ",end="")printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to segregate even and odd nodes and // return the head of the new listpublicstaticNodeSegregateEvenOdd(Nodehead){// Result list to hold even nodesNoderesStart=null;NoderesEnd=null;// Pointers for the original listNodecurr=head;Nodeprev=null;// Move all even nodes from original to resultwhile(curr!=null){// If current node is evenif(curr.data%2==0){// Remove the current even node // from the original listif(prev!=null){prev.next=curr.next;}else{// If the even node is at the headhead=curr.next;}// Add the current even node to the result listif(resStart==null){resStart=curr;resEnd=resStart;}else{resEnd.next=curr;resEnd=resEnd.next;}curr=curr.next;}else{// If the node is odd, just move to the nextprev=curr;curr=curr.next;}}// If there are no even nodes, return the original listif(resStart==null){returnhead;}// Append the remaining original // list (odd nodes) to the result listresEnd.next=head;// Return the result list (starting with even nodes)returnresStart;}// Function to print the linked listpublicstaticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}staticvoidMain(string[]args){// Create a sample linked list: 0->1->4->6->9->10->11Nodehead=newNode(0);head.next=newNode(1);head.next.next=newNode(4);head.next.next.next=newNode(6);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);head.next.next.next.next.next.next=newNode(11);Console.Write("Original Linked list: ");PrintList(head);head=SegregateEvenOdd(head);Console.Write("Modified Linked list: ");PrintList(head);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to segregate even and odd nodes and return the// head of the new listfunctionsegregateEvenOdd(head){// Result list to hold even nodesletresStart=null;letresEnd=null;// Pointers for the original listletcurr=head;letprev=null;// Move all even nodes from original to resultwhile(curr!==null){// If current node is evenif(curr.data%2===0){// Remove the current even node from the// original listif(prev!==null){prev.next=curr.next;}else{// If the even node is at the headhead=curr.next;}// Add the current even node to the result listif(resStart===null){resStart=curr;resEnd=resStart;}else{resEnd.next=curr;resEnd=resEnd.next;}curr=curr.next;}else{// If the node is odd, just move to the nextprev=curr;curr=curr.next;}}// If there are no even nodes, return the original listif(resStart===null){returnhead;}// Append the remaining original list (odd nodes) to the// result listresEnd.next=head;// Return the result list (starting with even nodes)returnresStart;}// Function to print the linked listfunctionprintList(node){letcurr=node;while(curr!==null){process.stdout.write(curr.data+" ");curr=curr.next;}process.stdout.write("\n");}// Create a sample linked list: 0->1->4->6->9->10->11lethead=newNode(0);head.next=newNode(1);head.next.next=newNode(4);head.next.next.next=newNode(6);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);head.next.next.next.next.next.next=newNode(11);process.stdout.write("Original Linked list: ");printList(head);head=segregateEvenOdd(head);process.stdout.write("Modified Linked list: ");printList(head);
Maintaining Start and End - O(n) Time and O(1) Space
The idea is to initialize pointers to track even and odd list separately. Traverse the list list end. While traversing the odd data node should be appended in odd list pointer and even data node should be appended in even list pointer and update the original list's head to the even list's head.
Step-by-step implementation:
Initialize pointers for even and odd list , say evenStart , evenEnd and oddStart , oddEnd.
Separate nodes into even and odd lists during traversal.
Link the end of the even list to the start of the odd list.
Update the original list's head to the even list's head.
Below is the implementation of the above approach. Note that we create dummy nodes to avoid extra condition checks in the while loop.
C++
#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to segregate even and odd nodes // and return the head of the new list.Node*segregateEvenOdd(Node*head){// We create dummy nodes to avoid extra // condition checks in the while loop.Node*eStart=newNode(0);Node*oStart=newNode(0);// Pointers to the end of the even and// odd listsNode*eEnd=eStart;Node*oEnd=oStart;// Node to traverse the listNode*curr=head;while(curr!=nullptr){intval=curr->data;// If current value is even, add it // to the even listif(val%2==0){eEnd->next=curr;eEnd=eEnd->next;}else{// Else to the odd listoEnd->next=curr;oEnd=oEnd->next;}// Move to the next nodecurr=curr->next;}// Terminate the odd listoEnd->next=nullptr;// Combine even and odd listseEnd->next=oStart->next;// Return the new head of the // combined list (even head)Node*newHead=eStart->next;// Clean up starting dummy nodesdeleteeStart;deleteoStart;returnnewHead;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}}intmain(){// Let us create a sample linked list as following// 0->1->4->6->9->10->11Node*head=newNode(0);head->next=newNode(1);head->next->next=newNode(4);head->next->next->next=newNode(6);head->next->next->next->next=newNode(9);head->next->next->next->next->next=newNode(10);head->next->next->next->next->next->next=newNode(11);cout<<"Original Linked list: ";printList(head);head=segregateEvenOdd(head);cout<<"\nModified Linked list: ";printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to create a new nodestructNode*newNode(intx){structNode*temp=(structNode*)malloc(sizeof(structNode));temp->data=x;temp->next=NULL;returntemp;}// Function to segregate even and odd nodes // and return the head of the new list.structNode*segregateEvenOdd(structNode*head){// We create dummy nodes to avoid extra // condition checks in the while loop.structNode*eStart=newNode(0);structNode*oStart=newNode(0);// Pointers to the end of the even and odd listsstructNode*eEnd=eStart;structNode*oEnd=oStart;// Node to traverse the liststructNode*curr=head;while(curr!=NULL){intval=curr->data;// If current value is even, add it to the even listif(val%2==0){eEnd->next=curr;eEnd=eEnd->next;}else{// Else to the odd listoEnd->next=curr;oEnd=oEnd->next;}// Move to the next nodecurr=curr->next;}// Terminate the odd listoEnd->next=NULL;// Combine even and odd listseEnd->next=oStart->next;// Return the new head of the combined list (even head)structNode*newHead=eStart->next;// Clean up dummy nodesfree(eStart);free(oStart);returnnewHead;}// Function to print the linked listvoidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}}intmain(){// Let us create a sample linked list as following// 0->1->4->6->9->10->11structNode*head=newNode(0);head->next=newNode(1);head->next->next=newNode(4);head->next->next->next=newNode(6);head->next->next->next->next=newNode(9);head->next->next->next->next->next=newNode(10);head->next->next->next->next->next->next=newNode(11);printf("Original Linked list: ");printList(head);head=segregateEvenOdd(head);printf("\nModified Linked list: ");printList(head);return0;}
Java
importjava.util.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}publicclassGfG{// Function to segregate even and odd nodes// and return the head of the new list.publicstaticNodesegregateEvenOdd(Nodehead){// We create dummy nodes to avoid extra // condition checks in the while loop.NodeeStart=newNode(0);NodeoStart=newNode(0);// Pointers to the end of the even and odd listsNodeeEnd=eStart;NodeoEnd=oStart;// Node to traverse the listNodecurr=head;while(curr!=null){intval=curr.data;// If current value is even, add it to the even listif(val%2==0){eEnd.next=curr;eEnd=eEnd.next;}else{// Else to the odd listoEnd.next=curr;oEnd=oEnd.next;}// Move to the next nodecurr=curr.next;}// Terminate the odd listoEnd.next=null;// Combine even and odd listseEnd.next=oStart.next;// Return the new head of the combined list (even head)returneStart.next;}// Function to print the linked listpublicstaticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}}publicstaticvoidmain(String[]args){// Let us create a sample linked list as following// 0->1->4->6->9->10->11Nodehead=newNode(0);head.next=newNode(1);head.next.next=newNode(4);head.next.next.next=newNode(6);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);head.next.next.next.next.next.next=newNode(11);System.out.print("Original Linked list: ");printList(head);head=segregateEvenOdd(head);System.out.print("\nModified Linked list: ");printList(head);}}
Python
classNode:def__init__(self,data):self.data=dataself.next=None# Function to segregate even and odd nodes# and return the head of the new list.defsegregateEvenOdd(head):# We create dummy nodes to avoid extra # condition checks in the while loop.eStart=Node(0)oStart=Node(0)# Pointers to the end of the even and odd listseEnd=eStartoEnd=oStart# Node to traverse the listcurr=headwhilecurr:val=curr.data# If current value is even, add it to the even listifval%2==0:eEnd.next=curreEnd=eEnd.nextelse:# Else to the odd listoEnd.next=curroEnd=oEnd.next# Move to the next nodecurr=curr.next# Terminate the odd listoEnd.next=None# Combine even and odd listseEnd.next=oStart.next# Return the new head of the combined list (even head)returneStart.next# Function to print the linked listdefprintList(node):whilenode:print(node.data,end=" ")node=node.nextif__name__=="__main__":# Let us create a sample linked list as following# 0->1->4->6->9->10->11head=Node(0)head.next=Node(1)head.next.next=Node(4)head.next.next.next=Node(6)head.next.next.next.next=Node(9)head.next.next.next.next.next=Node(10)head.next.next.next.next.next.next=Node(11)print("Original Linked list: ",end="")printList(head)head=segregateEvenOdd(head)print("\nModified Linked list: ",end="")printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to segregate even and odd nodes// and return the head of the new list.publicstaticNodeSegregateEvenOdd(Nodehead){// We create dummy nodes to avoid extra // condition checks in the while loop.NodeeStart=newNode(0);NodeoStart=newNode(0);// Pointers to the end of the even and odd listsNodeeEnd=eStart;NodeoEnd=oStart;// Node to traverse the listNodecurr=head;while(curr!=null){intval=curr.data;// If current value is even, add it to the even listif(val%2==0){eEnd.next=curr;eEnd=eEnd.next;}else{// Else to the odd listoEnd.next=curr;oEnd=oEnd.next;}// Move to the next nodecurr=curr.next;}// Terminate the odd listoEnd.next=null;// Combine even and odd listseEnd.next=oStart.next;// Return the new head of the combined list (even head)returneStart.next;}// Function to print the linked listpublicstaticvoidPrintList(Nodenode){Nodecurr=node;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}}publicstaticvoidMain(){// Let us create a sample linked list as following// 0->1->4->6->9->10->11Nodehead=newNode(0);head.next=newNode(1);head.next.next=newNode(4);head.next.next.next=newNode(6);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);head.next.next.next.next.next.next=newNode(11);Console.Write("Original Linked list: ");PrintList(head);head=SegregateEvenOdd(head);Console.Write("\nModified Linked list: ");PrintList(head);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to segregate even and odd nodes// and return the head of the new list.functionsegregateEvenOdd(head){// We create dummy nodes to avoid extra// condition checks in the while loop.leteStart=newNode(0);letoStart=newNode(0);// Pointers to the end of the even and odd listsleteEnd=eStart;letoEnd=oStart;// Node to traverse the listletcurr=head;while(curr!==null){letval=curr.data;// If current value is even, add it to the even listif(val%2===0){eEnd.next=curr;eEnd=eEnd.next;}else{// Else to the odd listoEnd.next=curr;oEnd=oEnd.next;}// Move to the next nodecurr=curr.next;}// Terminate the odd listoEnd.next=null;// Combine even and odd listseEnd.next=oStart.next;// Return the new head of the combined list (even head)returneStart.next;}// Function to print the linked listfunctionprintList(node){letcurr=node;while(curr!==null){process.stdout.write(curr.data+" ");curr=curr.next;}}// Let us create a sample linked list as following// 0->1->4->6->9->10->11lethead=newNode(0);head.next=newNode(1);head.next.next=newNode(4);head.next.next.next=newNode(6);head.next.next.next.next=newNode(9);head.next.next.next.next.next=newNode(10);head.next.next.next.next.next.next=newNode(11);process.stdout.write("Original Linked list: ");printList(head);head=segregateEvenOdd(head);process.stdout.write("\nModified Linked list: ");printList(head);