VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

Segregate even and odd nodes in a Linked List

Last Updated : 27 May, 2026

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:

👁 2056958077

Output:

👁 2056958078

Explanation: 8,2,4,6 are the even numbers so they appear first and 17,15,9 are odd numbers that appear later.

Input:

👁 2056958079

Output:

👁 2056958080

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


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.

Output
8->2->4->6->17->15->9

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment
Article Tags: