Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Segregate even and odd nodes in a Linked List using Deque

  • Difficulty Level : Easy
  • Last Updated : 05 Nov, 2021

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 -> NULL
Input: 4 -> 3 -> 2 -> 1 -> NULL 
Output: 2 -> 4 -> 3 -> 1 -> NULL 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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 function
changes 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 off the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
// printing the linked list
void 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 deque
void 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 code
int 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 off
  // 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 deque
import 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 off 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
def 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 deque
def 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 = None
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)
     
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 off
  // 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 off
        // 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>


Output: 

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

 

Time complexity: O(N) 
Auxiliary Space: O(N), where N is the total number of nodes in the linked list.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!