VOOZH about

URL: https://www.geeksforgeeks.org/dsa/segregate-even-and-odd-nodes-in-a-linked-list-using-deque/

⇱ Segregate even and odd nodes in a Linked List using Deque - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Segregate even and odd nodes in a Linked List using Deque

Last Updated : 11 Jul, 2025

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 

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:  


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 

Complexity Analysis:

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