Segregate even and odd nodes in a Linked List
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->NULLInput: 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 a 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.
Follow the steps below to implement the above idea:
- Get a 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 of 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 << "\nModified Linked list " ; printList(head); return 0; } // This code is contributed by rathbhupendra |
C
// C 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; }; void segregateEvenOdd( struct Node **head_ref) { struct Node *end = *head_ref; struct Node *prev = NULL; struct Node *curr = *head_ref; /* Get pointer to the last node */ while (end->next != NULL) end = end->next; struct 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( 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 of 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 program to test above functions*/ int main() { /* Start with the empty list */ struct 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); printf ( "\nOriginal Linked list \n" ); printList(head); segregateEvenOdd(&head); printf ( "\nModified Linked list \n" ); printList(head); return 0; } |
Java
// Java program to segregate even and odd nodes in a // Linked List import java.io.*; import java.util.*; class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node( int d) { data = d; next = null ; } } void segregateEvenOdd() { Node end = head; Node prev = null ; Node curr = head; /* Get pointer to last Node */ while (end.next != null ) end = end.next; Node new_end = end; // Consider all odd nodes before getting first even // node while (curr.data % 2 != 0 && curr != end) { new_end.next = curr; curr = curr.next; new_end.next.next = null ; new_end = new_end.next; } // do following steps only if there is an even node if (curr.data % 2 == 0 ) { head = curr; // now curr points to first even node while (curr != end) { if (curr.data % 2 == 0 ) { prev = curr; curr = curr.next; } else { /* Break the link between prev and * curr*/ 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 curr pointer */ curr = prev.next; } } } /* We have to set prev before executing rest of this * code */ else prev = curr; if (new_end != end && end.data % 2 != 0 ) { prev.next = end.next; end.next = null ; new_end.next = end; } } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push( int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Utility function to print a linked list void printList() { Node temp = head; while (temp != null ) { System.out.print(temp.data + " " ); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push( 11 ); llist.push( 10 ); llist.push( 8 ); llist.push( 6 ); llist.push( 4 ); llist.push( 2 ); llist.push( 0 ); System.out.println( "Original Linked List" ); llist.printList(); llist.segregateEvenOdd(); System.out.println( "Modified Linked List" ); llist.printList(); } } /* This code is contributed by Rajat Mishra */ |
Python
# Python program to segregate even and odd nodes in a # Linked List head = None # head of list # Node class class Node: # Function to initialise the node object def __init__( self , data): self .data = data # Assign data self . next = None def segregateEvenOdd(): global head end = head prev = None curr = head # Get pointer to last Node while (end. next ! = None ): end = end. next new_end = end # Consider all odd nodes before getting first even node while (curr.data % 2 ! = 0 and curr ! = end): new_end. next = curr curr = curr. next new_end. next . next = None new_end = new_end. next # do following steps only if there is an even node if (curr.data % 2 = = 0 ): head = curr # now curr points to first even node while (curr ! = end): if (curr.data % 2 = = 0 ): prev = curr curr = curr. next else : # Break the link between prev and curr prev. next = curr. next # Make next of curr as None curr. next = None # Move curr to end new_end. next = curr # Make curr as new end of list new_end = curr # Update curr pointer curr = prev. next # We have to set prev before executing rest of this code else : prev = curr if (new_end ! = end and end.data % 2 ! = 0 ): prev. next = end. next end. next = None new_end. next = end # Given a reference (pointer to pointer) to the head # of a list and an int, push a new node on the front # of the list. def push(new_data): global head # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node. next = head # 4. Move the head to point to new Node head = new_node # Utility function to print a linked list def printList(): global head temp = head while (temp ! = None ): print (temp.data, end = " " ) temp = temp. next print ( " " ) # Driver program to test above functions push( 11 ) push( 10 ) push( 8 ) push( 6 ) push( 4 ) push( 2 ) push( 0 ) print ( "Original Linked List" ) printList() segregateEvenOdd() print ( "Modified Linked List" ) printList() # This code is contributed by Arnab Kundu |
C#
// C# program to segregate even and odd nodes in a // Linked List using System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node( int d) { data = d; next = null ; } } void segregateEvenOdd() { Node end = head; Node prev = null ; Node curr = head; /* Get pointer to last Node */ while (end.next != null ) end = end.next; Node new_end = end; // Consider all odd nodes before // getting first even node while (curr.data % 2 != 0 && curr != end) { new_end.next = curr; curr = curr.next; new_end.next.next = null ; new_end = new_end.next; } // do following steps only // if there is an even node if (curr.data % 2 == 0) { head = curr; // now curr points to first even node while (curr != end) { if (curr.data % 2 == 0) { prev = curr; curr = curr.next; } else { /* Break the link between prev and curr*/ 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 curr pointer */ curr = prev.next; } } } /* We have to set prev before executing rest of this code */ else prev = curr; if (new_end != end && end.data % 2 != 0) { prev.next = end.next; end.next = null ; new_end.next = end; } } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push( int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Utility function to print a linked list void printList() { Node temp = head; while (temp != null ) { Console.Write(temp.data + " " ); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String []args) { LinkedList llist = new LinkedList(); llist.push(11); llist.push(10); llist.push(8); llist.push(6); llist.push(4); llist.push(2); llist.push(0); Console.WriteLine( "Original Linked List" ); llist.printList(); llist.segregateEvenOdd(); Console.WriteLine( "Modified Linked List" ); llist.printList(); } } // This code has been contributed by 29AjayKumar |
Javascript
<script> // javascript program to segregate even and odd nodes in a // Linked List var head; // head of list /* Linked list Node */ class Node { constructor(val) { this .data = val; this .next = null ; } } function segregateEvenOdd() { var end = head; var prev = null ; var curr = head; /* Get pointer to last Node */ while (end.next != null ) end = end.next; var new_end = end; // Consider all odd nodes before getting first even node while (curr.data % 2 != 0 && curr != end) { new_end.next = curr; curr = curr.next; new_end.next.next = null ; new_end = new_end.next; } // do following steps only if there is an even node if (curr.data % 2 == 0) { head = curr; // now curr points to first even node while (curr != end) { if (curr.data % 2 == 0) { prev = curr; curr = curr.next; } else { /* Break the link between prev and curr */ 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 curr pointer */ curr = prev.next; } } } /* We have to set prev before executing rest of this code */ else prev = curr; if (new_end != end && end.data % 2 != 0) { prev.next = end.next; end.next = null ; new_end.next = end; } } /* * Given a reference (pointer to pointer) to the head of a list and an int, push * a new node on the front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Utility function to print a linked list function printList() { var temp = head; while (temp != null ) { document.write(temp.data + " " ); temp = temp.next; } document.write(); } /* Driver program to test above functions */ push(11); push(10); push(8); push(6); push(4); push(2); push(0); document.write( "Original Linked List " ); printList(); document.write( "<br>" ); segregateEvenOdd(); document.write( "Modified Linked List " ); // This code contributed by umadevi9616 </script> |
Original Linked list 0 2 4 6 8 10 11 Modified Linked list 0 2 4 6 8 10 11
Time Complexity: O(n), As we are only traversing linearly through the list.
Auxiliary Space: O(1)
Thanks to blunderboy for suggesting this method.
Method 2:
The idea is to split the linked list into two: one containing all even nodes and the 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 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 same, we must insert all the odd nodes at the end of the even node list. And to do that in constant time, we must keep track of last pointer in the even node list.
Below is the implementation of the above approach:
C++
// CPP 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 */ 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(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 of 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 program to test above functions*/ int main() { /* Start with the empty list */ 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); cout << "Original Linked list" << endl; printList(head); segregateEvenOdd(&head); cout << endl << "Modified Linked list " << endl; printList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
C
// C program to segregate even and odd nodes in a // Linked List #include <stdio.h> #include <stdlib.h> /* a node of the singly linked list */ typedef struct Node { int data; struct Node* next; } Node; // Function to segregate even and odd nodes. void segregateEvenOdd(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(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = (Node*) malloc ( sizeof (Node)); /* put in the data */ new_node->data = new_data; /* link the old list of 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) { printf ( "%d " , node->data); node = node->next; } } /* Driver program to test above functions*/ 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 ( "\nOriginal Linked list \n" ); printList(head); segregateEvenOdd(&head); printf ( "\nModified Linked list \n" ); printList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129) |
Java
// Java program to segregate even and odd nodes in a // Linked List import java.util.*; import java.io.*; class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node( int d) { data = d; next = null ; } } public void segregateEvenOdd() { Node evenStart = null ; Node evenEnd = null ; Node oddStart = null ; Node oddEnd = null ; Node currentNode = head; while (currentNode != null ) { int element = currentNode.data; if (element % 2 == 0 ) { if (evenStart == null ) { evenStart = currentNode; evenEnd = evenStart; } else { evenEnd.next = currentNode; evenEnd = evenEnd.next; } } else { if (oddStart == null ) { oddStart = currentNode; oddEnd = oddStart; } else { oddEnd.next = currentNode; oddEnd = oddEnd.next; } } // Move head pointer one step in forward direction currentNode = currentNode.next; } if (oddStart == null || evenStart == null ) { return ; } evenEnd.next = oddStart; oddEnd.next = null ; head=evenStart; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push( int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Utility function to print a linked list void printList() { Node temp = head; while (temp != null ) { System.out.print(temp.data+ " " ); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push( 11 ); llist.push( 10 ); llist.push( 9 ); llist.push( 6 ); llist.push( 4 ); llist.push( 1 ); llist.push( 0 ); System.out.println( "Original Linked List" ); llist.printList(); llist.segregateEvenOdd(); System.out.println( "Modified Linked List" ); llist.printList(); } } |
C#
// C# program to segregate even and odd nodes in a // Linked List using System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node( int d) { data = d; next = null ; } } public void segregateEvenOdd() { Node evenStart = null ; Node evenEnd = null ; Node oddStart = null ; Node oddEnd = null ; Node currentNode = head; while (currentNode != null ) { int element = currentNode.data; if (element % 2 == 0) { if (evenStart == null ) { evenStart = currentNode; evenEnd = evenStart; } else { evenEnd.next = currentNode; evenEnd = evenEnd.next; } } else { if (oddStart == null ) { oddStart = currentNode; oddEnd = oddStart; } else { oddEnd.next = currentNode; oddEnd = oddEnd.next; } } // Move head pointer one step in forward direction currentNode = currentNode.next; } if (oddStart == null || evenStart == null ) { return ; } evenEnd.next = oddStart; oddEnd.next = null ; head=evenStart; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push( int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Utility function to print a linked list void printList() { Node temp = head; while (temp != null ) { Console.Write(temp.data+ " " ); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main() { LinkedList llist = new LinkedList(); llist.push(11); llist.push(10); llist.push(9); llist.push(6); llist.push(4); llist.push(1); llist.push(0); Console.WriteLine( "Original Linked List" ); llist.printList(); llist.segregateEvenOdd(); Console.WriteLine( "Modified Linked List" ); llist.printList(); } } /* This code contributed by PrinciRaj1992 */ |
Python3
# Python3 program to segregate even and odd nodes in a # Linked List head = None # head of list # Node class class Node: # Function to initialise the node object def __init__( self , data): self .data = data # Assign data self . next = None # Function to segregate even and odd nodes. def segregateEvenOdd(): global head # Starting node of list having # even values. evenStart = None # Ending node of even values list. evenEnd = None # Starting node of odd values list. oddStart = None # Ending node of odd values list. oddEnd = None # Node to traverse the list. currNode = head while (currNode ! = None ): val = currNode.data # If current value is even, add # it to even values list. if (val % 2 = = 0 ): if (evenStart = = None ): 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 = = None ): 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 = = None or evenStart = = None ): return # Add odd list after even list. evenEnd . next = oddStart oddEnd . next = None # Modify head pointer to # starting of even list. head = evenStart ''' UTILITY FUNCTIONS ''' ''' Function to insert a node at the beginning ''' def push(new_data): global head # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node. next = head # 4. Move the head to point to new Node head = new_node ''' Function to print nodes in a given linked list ''' def printList(): global head node = head while (node ! = None ): print (node.data, end = " " ) node = node. next print () ''' Driver program to test above functions''' ''' Let us create a sample linked list as following 0.1.4.6.9.10.11 ''' push( 11 ) push( 10 ) push( 9 ) push( 6 ) push( 4 ) push( 1 ) push( 0 ) print ( "Original Linked list" ) printList() segregateEvenOdd() print ( "Modified Linked list" ) printList() # This code is contributed by shubhamsingh10. |
Javascript
<script> // JavaScript program to segregate // even and odd nodes in a // Linked List var head; // head of list /* Linked list Node*/ class Node { constructor(val) { this .data = val; this .next = null ; } } function segregateEvenOdd() { var evenStart = null ; var evenEnd = null ; var oddStart = null ; var oddEnd = null ; var currentNode = head; while (currentNode != null ) { var element = currentNode.data; if (element % 2 == 0) { if (evenStart == null ) { evenStart = currentNode; evenEnd = evenStart; } else { evenEnd.next = currentNode; evenEnd = evenEnd.next; } } else { if (oddStart == null ) { oddStart = currentNode; oddEnd = oddStart; } else { oddEnd.next = currentNode; oddEnd = oddEnd.next; } } // Move head pointer one // step in forward direction currentNode = currentNode.next; } if (oddStart == null || evenStart == null ) { return ; } evenEnd.next = oddStart; oddEnd.next = null ; head=evenStart; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Utility function to print a linked list function printList() { var temp = head; while (temp != null ) { document.write(temp.data+ " " ); temp = temp.next; } document.write( "<br/>" ); } /* Driver program to test above functions */ push(11); push(10); push(9); push(6); push(4); push(1); push(0); document.write( "Original Linked List<br/>" ); printList(); segregateEvenOdd(); document.write( "Modified Linked List<br/>" ); printList(); // This code is contributed by todaysgaurav </script> |
Original Linked list 0 1 4 6 9 10 11 Modified Linked list 0 4 6 10 1 9 11
Time Complexity: O(n), As we are only traversing linearly through the list.
Auxiliary Space: O(1)
Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem.
Method 3:
Using Queue data structure to solve this problem. Maintaining an even queue and an odd queue to get desired outputs.
C++
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; Node( int x) { data = x; next = NULL; } }; void p(Node* node) { while (node) { cout << node->data << " " ; node = node->next; } } Node* divide(Node* head) { queue<Node*> qe, qo,q; Node* cur = head; while (cur) { if (cur->data % 2 == 0) qe.push(cur); else qo.push(cur); cur = cur->next; } Node* node = new Node(-100); Node* ans = node; while (!qe.empty()) { q.push(qe.front()); qe.pop(); } while (!qo.empty()) { q.push(qo.front()); qo.pop(); } while (!q.empty()) { node->next = q.front(); node = q.front(); q.pop(); } node->next = NULL; return ans->next; } int main() { Node* head; head = new Node(9); head->next = new Node(1); head->next->next = new Node(6); head->next->next->next = new Node(7); head->next->next->next->next = new Node(3); head->next->next->next->next->next = new Node(4); Node* temp = divide(head); p(temp); return 0; } |
Java
// Java Program for the above approach import java.util.*; class Node{ int data; Node next; public Node( int x){ data = x; next = null ; } } class LinkList{ Node head; void p(Node node){ while (node != null ){ System.out.print(node.data + " " ); node = node.next; } } Node divide(Node head){ Queue<Node> qe = new LinkedList<Node>(); Queue<Node> qo = new LinkedList<Node>(); Queue<Node> q = new LinkedList<Node>(); Node cur = head; while (cur != null ){ if (cur.data % 2 == 0 ) qe.add(cur); else qo.add(cur); cur = cur.next; } Node node = new Node(- 100 ); Node ans = node; while (!qe.isEmpty()){ q.add(qe.poll()); } while (!qo.isEmpty()){ q.add(qo.poll()); } while (!q.isEmpty()){ node.next = q.poll(); node = node.next; } node.next = null ; return ans.next; } public static void main(String args[]){ LinkList llist = new LinkList(); llist.head = new Node( 9 ); llist.head.next = new Node( 1 ); llist.head.next.next = new Node( 6 ); llist.head.next.next.next = new Node( 7 ); llist.head.next.next.next.next = new Node( 3 ); llist.head.next.next.next.next.next = new Node( 4 ); Node temp = llist.divide(llist.head); llist.p(temp); } } // This code is contributed by Kirti Agarwal |
Python3
# Python program to segregate even and odd nodes # in a Linked List # A node structure class Node: def __init__( self , x): self .data = x self . next = None def p(node): while (node is not None ): print (node.data, end = " " ) node = node. next def divide(head): q = [] qe = [] qo = [] cur = head while (cur is not None ): if (cur.data % 2 = = 0 ): qe.append(cur) else : qo.append(cur) cur = cur. next node = Node( - 100 ) ans = node while ( len (qe) > 0 ): q.append(qe.pop( 0 )) while ( len (qo) > 0 ): q.append(qo.pop( 0 )) while ( len (q) > 0 ): node. next = q.pop( 0 ) node = node. next node. next = None return ans. next head = Node( 9 ) head. next = Node( 1 ) head. next . next = Node( 6 ) head. next . next . next = Node( 7 ) head. next . next . next . next = Node( 3 ) head. next . next . next . next . next = Node( 4 ) temp = divide(head) p(temp) # This code is contributed by Yash Agarwal(yashagrwal2852002) |
C#
// C# program to segregate even and odd nodes in a // Linked List using System; using System.Collections.Generic; public class LinkedList { public Node head; public class Node { public int data; public Node next; public Node( int x) { data = x; next = null ; } } void p(Node node){ while (node != null ){ Console.WriteLine(node.data + " " ); node = node.next; } } Node divide(Node head) { Queue<Node> qe = new Queue<Node>(); Queue<Node> qo = new Queue<Node>(); Queue<Node> q = new Queue<Node>(); Node cur = head; while (cur != null ){ if (cur.data%2 == 0) qe.Enqueue(cur); else qo.Enqueue(cur); cur = cur.next; } Node node = new Node(-100); Node ans = node; while (qe.Count != 0){ q.Enqueue(qe.Peek()); qe.Dequeue(); } while (qo.Count != 0){ q.Enqueue(qo.Peek()); qo.Dequeue(); } while (q.Count != 0){ node.next = q.Peek(); node = q.Peek(); q.Dequeue(); } node.next = null ; return ans.next; } public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.head = new Node(9); llist.head.next = new Node(1); llist.head.next.next = new Node(6); llist.head.next.next.next = new Node(7); llist.head.next.next.next.next = new Node(3); llist.head.next.next.next.next.next = new Node(4); Node temp = llist.divide(llist.head); llist.p(temp); } } // This code is contributed by Yash Agarwal(yashagarwal2852002) |
Javascript
// JavaScript Program for the above approach class Node{ constructor(x){ this .data = x; this .next = null ; } } function p(node){ while (node != null ){ document.write(node.data); node = node.next; } } function divide(head){ var q = []; var qe = []; var qo = []; var cur = head; while (cur != null ){ if (cur.data %2 == 0) qe.push(cur); else qo.push(cur); cur = cur.next; } var node = new Node(-100); ans = node; while (qe.length != 0){ q.push(qe.shift()); } while (qo.length != 0){ q.push(qo.shift()); } while (q.length != 0){ node.next = q.shift(); node = node.next; } node.next = null ; return ans.next; } var head = new Node(9); head.next = new Node(1); head.next.next = new Node(6); head.next.next.next = new Node(7); head.next.next.next.next = new Node(3); head.next.next.next.next.next = new Node(4); temp = divide(head); p(temp); // This code is contributed by Yash Agarwal(yashagarwal2852002) |
6 4 9 1 7 3
n= no.of nodes
Time Complexity: O(n)
Auxiliary Space: O(n)
// This code is contributed by Abhinav
Please Login to comment...