Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes the same as that of the original list, the task is just to rearrange the nodes such that all even valued nodes appear before the odd valued nodes.
See Also: Segregate even and odd nodes in a Linked List
Examples:Â
Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> NULLÂ
Output: 10 -> 8 -> 6 -> 4 -> 2 -> 1 -> 3 -> 5 -> 7 -> 9 -> NULLInput: 4 -> 3 -> 2 -> 1 -> NULLÂ
Output: 2 -> 4 -> 3 -> 1 -> NULLÂ
The idea is to iteratively push all the elements of the linked list to deque as per the below conditions:Â Â
- Start traversing the linked list and if an element is even then push it to the front of the Deque and,
- If the element is odd then push it to the back of the Deque.
Finally, replace all elements of the linked list with the elements of Deque starting from the first element.
Below is the implementation of the above approach:Â Â
C++
// CPP program to segregate even and// odd nodes in a linked list using deque#include <bits/stdc++.h>using namespace std;Â
/* Link list node */struct Node {Â Â Â Â int data;Â Â Â Â struct Node* next;};Â
/*UTILITY FUNCTIONS*//* Push a node to linked list. Note that this functionchanges the head */void push(struct Node** head_ref, char 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;}Â
// printing the linked listvoid printList(struct Node* head){Â Â Â Â struct Node* temp = head;Â Â Â Â while (temp != NULL) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â printf("%d ", temp->data);Â Â Â Â Â Â Â Â temp = temp->next;Â Â Â Â }}Â
// Function to rearrange even and odd// elements in a linked list using dequevoid evenOdd(struct Node* head){    struct Node* temp = head;         // Declaring a Deque    deque<int> d; Â
    // Push all the elements of    // linked list in to deque    while (temp != NULL) {Â
        // if element is even push it        // to front of the deque        if (temp->data % 2 == 0)             d.push_front(temp->data);Â
        else // else push at the back of the deque            d.push_back(temp->data);        temp = temp->next; // increase temp    }         temp = head;         // Replace all elements of the linked list    // with the elements of Deque starting from     // the first element    while (!d.empty()) {        temp->data = d.front();        d.pop_front();        temp = temp->next;     }}Â
// Driver codeint main(){Â Â Â Â struct Node* head = NULL;Â Â Â Â push(&head, 10);Â Â Â Â push(&head, 9);Â Â Â Â push(&head, 8);Â Â Â Â push(&head, 7);Â Â Â Â push(&head, 6);Â Â Â Â push(&head, 5);Â Â Â Â push(&head, 4);Â Â Â Â push(&head, 3);Â Â Â Â push(&head, 2);Â Â Â Â push(&head, 1);Â Â Â Â Â Â Â Â Â cout << "Given linked list: ";Â Â Â Â Â Â Â Â printList(head);Â Â Â Â Â Â Â Â Â Â Â Â Â evenOdd(head);Â Â Â Â Â Â Â Â Â cout << "\nAfter rearrangement: ";Â Â Â Â Â Â Â Â printList(head);Â Â Â Â Â Â Â Â Â Â Â Â Â return 0;} |
Java
// JAVA program to segregate // even and odd nodes in a // linked list using deque import java.util.*;class GFG{ Â
// Link list node static class Node {Â Â Â int data; Â Â Node next; }; Â
// UTILITY FUNCTIONS// Push a node to linked list. // Note that this function // changes the head static Node 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;   return head_ref;} Â
// Printing the linked list static void printList(Node head) { Â Â Node temp = head; Â Â while (temp != null) Â Â { Â Â Â Â System.out.printf("%d ", Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â temp.data); Â Â Â Â temp = temp.next; Â Â } } Â
// Function to rearrange even // and odd elements in a linked // list using deque static void evenOdd(Node head) { Â Â Node temp = head; Â
  // Declaring a Deque   Deque<Integer> d =         new LinkedList<>(); Â
  // Push all the elements of   // linked list in to deque   while (temp != null)   {    // if element is even push it     // to front of the deque     if (temp.data % 2 == 0)       d.addFirst(temp.data); Â
    else             // else push at the       // back of the deque       d.add(temp.data);         // increase temp     temp = temp.next;   } Â
  temp = head; Â
  // Replace all elements of   // the linked list with the   // elements of Deque starting   // from the first element   while (!d.isEmpty())   {     temp.data = d.peek();     d.pollFirst();     temp = temp.next;   } } Â
// Driver code public static void main(String[] args) { Â Â Node head = null; Â Â head = push(head, 10); Â Â head = push(head, 9); Â Â head = push(head, 8); Â Â head = push(head, 7); Â Â head = push(head, 6); Â Â head = push(head, 5); Â Â head = push(head, 4); Â Â head = push(head, 3); Â Â head = push(head, 2); Â Â head = push(head, 1); Â
  System.out.print("Given linked list: ");   printList(head); Â
  evenOdd(head); Â
  System.out.print("\nAfter rearrangement: ");   printList(head);        }} Â
// This code is contributed by shikhasingrajput |
Python
# Python program to segregate even and# odd nodes in a linked list using dequeimport collectionsÂ
# Node class class Node:          # Function to initialise the node object     def __init__(self, data):         self.data = data # Assign data         self.next = NoneÂ
# UTILITY FUNCTIONS# Push a node to linked list. Note that this function# changes the head def push( head_ref, new_data):Â
    # allocate node     new_node = Node(0)Â
    # 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         return head_refÂ
# printing the linked listdef printList( head):Â
    temp = head    while (temp != None):         print( temp.data, end = " ")        temp = temp.next     # Function to rearrange even and odd# elements in a linked list using dequedef evenOdd( head):Â
    temp = head         # Declaring a Deque    d = collections.deque([]) Â
    # Push all the elements of    # linked list in to deque    while (temp != None) :Â
        # if element is even push it        # to front of the deque        if (temp.data % 2 == 0):             d.appendleft(temp.data)Â
        else: # else push at the back of the deque            d.append(temp.data)        temp = temp.next # increase temp         temp = head         # Replace all elements of the linked list    # with the elements of Deque starting from     # the first element    while (len(d) > 0) :        temp.data = d[0]        d.popleft()        temp = temp.next     # Driver codeÂ
head = Nonehead = push(head, 10)head = push(head, 9)head = push(head, 8)head = push(head, 7)head = push(head, 6)head = push(head, 5)head = push(head, 4)head = push(head, 3)head = push(head, 2)head = push(head, 1)Â Â Â Â Â print( "Given linked list: ", end = "")printList(head)Â Â Â Â Â Â Â Â Â evenOdd(head)Â Â Â Â Â print("\nAfter rearrangement: ", end = "")printList(head)Â
# This code is contributed by Arnab Kundu |
C#
// C# program to segregate // even and odd nodes in a // linked list using deque using System;using System.Collections.Generic;class GFG{ Â
// Link list node public class Node {Â Â Â public int data; Â Â public Node next; }; Â
// UTILITY FUNCTIONS// Push a node to linked list. // Note that this function // changes the head static Node 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;   return head_ref;} Â
// Printing the linked list static void printList(Node head) { Â Â Node temp = head; Â Â while (temp != null) Â Â { Â Â Â Â Console.Write(" " + temp.data); Â Â Â Â temp = temp.next; Â Â } } Â
// Function to rearrange even // and odd elements in a linked // list using deque static void evenOdd(Node head) { Â Â Node temp = head; Â
  // Declaring a Deque   List<int> d =        new List<int>(); Â
  // Push all the elements of   // linked list in to deque   while (temp != null)   {    // if element is even push it     // to front of the deque     if (temp.data % 2 == 0)       d.Insert(0, temp.data); Â
    else             // else push at the       // back of the deque       d.Add(temp.data);         // increase temp     temp = temp.next;   } Â
  temp = head; Â
  // Replace all elements of   // the linked list with the   // elements of Deque starting   // from the first element   while (d.Count != 0)   {     temp.data = d[0];     d.RemoveAt(0);    temp = temp.next;   } } Â
// Driver code public static void Main(String[] args) { Â Â Node head = null; Â Â head = push(head, 10); Â Â head = push(head, 9); Â Â head = push(head, 8); Â Â head = push(head, 7); Â Â head = push(head, 6); Â Â head = push(head, 5); Â Â head = push(head, 4); Â Â head = push(head, 3); Â Â head = push(head, 2); Â Â head = push(head, 1); Â
  Console.Write("Given linked list: ");   printList(head); Â
  evenOdd(head); Â
  Console.Write("\nAfter rearrangement: ");   printList(head);        }} Â
// This code is contributed by 29AjayKumar |
Javascript
<script>      // JavaScript program to segregate      // even and odd nodes in a      // linked list using deque      // Link list node      class Node {        constructor() {          this.data = 0;          this.next = null;        }      }Â
      // UTILITY FUNCTIONS      // Push a node to linked list.      // Note that this function      // changes the head      function push(head_ref, new_data) {        // allocate node        var 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;        return head_ref;      }Â
      // Printing the linked list      function printList(head) {        var temp = head;        while (temp != null) {          document.write(" " + temp.data);          temp = temp.next;        }      }Â
      // Function to rearrange even      // and odd elements in a linked      // list using deque      function evenOdd(head) {        var temp = head;Â
        // Declaring a Deque        var d = [];Â
        // Push all the elements of        // linked list in to deque        while (temp != null) {          // if element is even push it          // to front of the deque          if (temp.data % 2 == 0) d.unshift(temp.data);          // else push at the          // back of the deque          else d.push(temp.data);Â
          // increase temp          temp = temp.next;        }Â
        temp = head;Â
        // Replace all elements of        // the linked list with the        // elements of Deque starting        // from the first element        while (d.length != 0) {          temp.data = d[0];          d.shift();          temp = temp.next;        }      }Â
      // Driver code      var head = null;      head = push(head, 10);      head = push(head, 9);      head = push(head, 8);      head = push(head, 7);      head = push(head, 6);      head = push(head, 5);      head = push(head, 4);      head = push(head, 3);      head = push(head, 2);      head = push(head, 1);Â
      document.write("Given linked list: ");      printList(head);Â
      evenOdd(head);Â
      document.write("<br>After rearrangement: ");      printList(head);             // This code is contributed by rdtank.    </script> |
Given linked list: 1 2 3 4 5 6 7 8 9 10 After rearrangement: 10 8 6 4 2 1 3 5 7 9
Complexity Analysis:
- Time complexity: O(N)Â
- Auxiliary Space: O(N), where N is the total number of nodes in the linked list.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Read More Information here on that Topic: geeksforgeeks.org/segregate-even-and-odd-nodes-in-a-linked-list-using-deque/ […]
… [Trackback]
[…] Information to that Topic: geeksforgeeks.org/segregate-even-and-odd-nodes-in-a-linked-list-using-deque/ […]
… [Trackback]
[…] Info on that Topic: geeksforgeeks.org/segregate-even-and-odd-nodes-in-a-linked-list-using-deque/ […]
… [Trackback]
[…] Read More to that Topic: geeksforgeeks.org/segregate-even-and-odd-nodes-in-a-linked-list-using-deque/ […]