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:
Output:
Explanation: 8,2,4,6 are the even numbers so they appear first and 17,15,9 are odd numbers that appear later.
Input:
Output:
Explanation: There is no even number. So no need for modification.
Extraction of Even and Appending Odds - O(n) Time O(1) Space
The Idea is to traverse the list and extract all even nodes while maintaining order. Build a separate even list and finally append the remaining odd nodes.
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<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intval){data=val;next=nullptr;}};Node*divide(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 headhead=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;}// Driver Codeintmain(){// Creating linked list: 17->15->8->9->2->4->6Node*head=newNode(17);head->next=newNode(15);head->next->next=newNode(8);head->next->next->next=newNode(9);head->next->next->next->next=newNode(2);head->next->next->next->next->next=newNode(4);head->next->next->next->next->next->next=newNode(6);head=divide(head);Node*curr=head;while(curr!=nullptr){cout<<curr->data;if(curr->next!=nullptr)cout<<"->";curr=curr->next;}return0;}
Java
importjava.util.*;classNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}publicclassGfG{publicstaticNodedivide(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;}// 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==null)returnhead;// Append the remaining original list// (odd nodes) to the result listresEnd.next=head;// Return the result list (starting with even nodes)returnresStart;}publicstaticvoidmain(String[]args){// Creating linked list: 17->15->8->9->2->4->6Nodehead=newNode(17);head.next=newNode(15);head.next.next=newNode(8);head.next.next.next=newNode(9);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(4);head.next.next.next.next.next.next=newNode(6);head=divide(head);Nodecurr=head;while(curr!=null){System.out.print(curr.data);if(curr.next!=null)System.out.print("->");curr=curr.next;}}}
Python
classNode:def__init__(self,val):self.data=valself.next=Nonedefdivide(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.next# If the node is odd, just move to the nextelse:prev=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# Driver Codeif__name__=='__main__':# Creating linked list: 17->15->8->9->2->4->6head=Node(17)head.next=Node(15)head.next.next=Node(8)head.next.next.next=Node(9)head.next.next.next.next=Node(2)head.next.next.next.next.next=Node(4)head.next.next.next.next.next.next=Node(6)head=divide(head)curr=headwhilecurrisnotNone:print(curr.data,end=''ifcurr.nextisNoneelse'->')curr=curr.next
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intval){data=val;next=null;}}publicclassGfG{publicstaticNodedivide(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;}// 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==null)returnhead;// Append the remaining original list// (odd nodes) to the result listresEnd.next=head;// Return the result list (starting with even nodes)returnresStart;}publicstaticvoidMain(){// Creating linked list: 17->15->8->9->2->4->6Nodehead=newNode(17);head.next=newNode(15);head.next.next=newNode(8);head.next.next.next=newNode(9);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(4);head.next.next.next.next.next.next=newNode(6);head=divide(head);Nodecurr=head;while(curr!=null){Console.Write(curr.data);if(curr.next!=null)Console.Write("->");curr=curr.next;}}}
JavaScript
classNode{constructor(val){this.data=val;this.next=null;}}functiondivide(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;}// 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===null)returnhead;// Append the remaining original list// (odd nodes) to the result listresEnd.next=head;// Return the result list (starting with even nodes)returnresStart;}// Driver Codelethead=newNode(17);head.next=newNode(15);head.next.next=newNode(8);head.next.next.next=newNode(9);head.next.next.next.next=newNode(2);head.next.next.next.next.next=newNode(4);head.next.next.next.next.next.next=newNode(6);head=divide(head);letcurr=head;while(curr!==null){process.stdout.write(curr.data.toString());if(curr.next!==null)process.stdout.write("->");curr=curr.next;}
Output
8->2->4->6->17->15->9
Time Complexity: O(n) Auxiliary Space: O(1)
Maintaining Start and End - O(n) Time O(1) Space
The idea is to maintain two separate lists for even and odd nodes using dummy nodes. During traversal, append nodes to their respective lists and finally connect the even list to the odd list.
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.
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*divide(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=divide(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*divide(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=divide(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.publicstaticNodedivide(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=divide(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.defdivide(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=divide(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.publicstaticNodedivide(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=divide(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.functiondivide(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=divide(head);process.stdout.write("\nModified Linked list: ");printList(head);