Open In App

Segregate even and odd nodes in a Linked List

Last Updated : 07 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL
Explanation: In the output list, we have all the even nodes first (in the same order as input list, then all the odd nodes of the list (in the same order as input list).

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

Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL
Explanation: We do not change the list as all the numbers are even.

Move Even and Append Remaining - O(n) Time and O(1) Space

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

C++
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int x) {
        data = x;
        next = nullptr;
    }
};

Node* segregateEvenOdd(Node* head) {
  
    // Result list to hold even nodes
    Node* resStart = nullptr;
    Node* resEnd = nullptr;

    // Pointers for the original list
    Node* curr = head;
    Node* prev = nullptr;

    // Move all even nodes from original
    // to result
    while (curr != nullptr) {
      
        // If current node is even
        if (curr->data % 2 == 0) {
          
            // Remove the current even node 
            // from the original list
            if (prev != nullptr) {
                prev->next = curr->next;
            } else {
              
                // If the even node is at the head 
                head = curr->next; 
            }

            // Add the current even node to the result list
            if (resStart == nullptr) {
                resStart = curr;
                resEnd = resStart;
            } else {
                resEnd->next = curr;
                resEnd = resEnd->next;
            }

            curr = curr->next;
        } 
      
        // If the node is odd, just move to the next
        else {            
            prev = curr;
            curr = curr->next;
        }
    }

    // If there are no even nodes, return
    // the original list
    if (resStart == nullptr)
        return head;

    // Append the remaining original list
    // (odd nodes) to the result list
    resEnd->next = head;

    // Return the result list (starting with even nodes)
    return resStart;
}

void printList(Node* node) {
    while (node != nullptr) {
        cout << node->data << " ";
        node = node->next;
    }
}

int main() {
    // Let us create a sample linked list as following
    // 0->1->4->6->9->10->11
    Node* head = new Node(0);
    head->next = new Node(1);
    head->next->next = new Node(4);
    head->next->next->next = new Node(6);
    head->next->next->next->next = new Node(9);
    head->next->next->next->next->next = new Node(10);
    head->next->next->next->next->next->next = new Node(11);

    cout << "Original Linked list: ";
    printList(head);

    head = segregateEvenOdd(head);

    cout << "\nModified Linked list: ";
    printList(head);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* newNode(int x) {
    struct Node* temp = 
        (struct Node*)malloc(sizeof(struct Node));
    temp->data = x;
    temp->next = NULL;
    return temp;
}

// Function to segregate even and odd nodes 
// and return the head of the new list
struct Node* segregateEvenOdd(struct Node* head) {
  
    // Result list to hold even nodes
    struct Node* resStart = NULL;
    struct Node* resEnd = NULL;

    // Pointers for the original list
    struct Node* curr = head;
    struct Node* prev = NULL;

    // Move all even nodes from original to result
    while (curr != NULL) {
      
        // If current node is even
        if (curr->data % 2 == 0) {
          
            // Remove the current even node
            // from the original list
            if (prev != NULL) {
                prev->next = curr->next;
            } else {
                // If the even node is at the head
                head = curr->next;
            }

            // Add the current even node to the result list
            if (resStart == NULL) {
                resStart = curr;
                resEnd = resStart;
            } else {
                resEnd->next = curr;
                resEnd = resEnd->next;
            }

            curr = curr->next;
        } else {
            // If the node is odd, just move to the next
            prev = curr;
            curr = curr->next;
        }
    }

    // If there are no even nodes, return the original list
    if (resStart == NULL) {
        return head;
    }

    // Append the remaining original list
    // (odd nodes) to the result list
    resEnd->next = head;

    // Return the result list (starting with even nodes)
    return resStart;
}

// Function to print the linked list
void printList(struct Node* node) {
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
    printf("\n");
}

int main() {
    // Create a sample linked list: 0->1->4->6->9->10->11
    struct Node* head = newNode(0);
    head->next = newNode(1);
    head->next->next = newNode(4);
    head->next->next->next = newNode(6);
    head->next->next->next->next = newNode(9);
    head->next->next->next->next->next = newNode(10);
    head->next->next->next->next->next->next = newNode(11);

    printf("Original Linked list: ");
    printList(head);

    head = segregateEvenOdd(head);

    printf("Modified Linked list: ");
    printList(head);

    return 0;
}
Java
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    // Function to segregate even and odd nodes 
    // and return the head of the new list.
    public static Node segregateEvenOdd(Node head) {

        // Result list to hold even nodes
        Node resStart = null;
        Node resEnd = null;

        // Pointers for the original list
        Node curr = head;
        Node prev = null;

        // Move all even nodes from original to result
        while (curr != null) {

            // If current node is even
            if (curr.data % 2 == 0) {

                // Remove the current even node from the original list
                if (prev != null) {
                    prev.next = curr.next;
                } else {
                    // If the even node is at the head
                    head = curr.next;
                }

                // Add the current even node to the result list
                if (resStart == null) {
                    resStart = curr;
                    resEnd = resStart;
                } else {
                    resEnd.next = curr;
                    resEnd = resEnd.next;
                }

                // Move to the next node
                curr = curr.next;
            } else { // If the node is odd, just move to the next
                prev = curr;
                curr = curr.next;
            }
        }

        // If there are no even nodes, return the original list
        if (resStart == null) {
            return head;
        }

        // Append the remaining original list
        // (odd nodes) to the result list
        resEnd.next = head;

        // Return the result list (starting with even nodes)
        return resStart;
    }

    // Function to print the linked list
    public static void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }

    public static void main(String[] args) {
        // Let us create a sample linked list as following
        // 0->1->4->6->9->10->11
        Node head = new Node(0);
        head.next = new Node(1);
        head.next.next = new Node(4);
        head.next.next.next = new Node(6);
        head.next.next.next.next = new Node(9);
        head.next.next.next.next.next = new Node(10);
        head.next.next.next.next.next.next = new Node(11);

        System.out.print("Original Linked list: ");
        printList(head);

        head = segregateEvenOdd(head);

        System.out.print("\nModified Linked list: ");
        printList(head);
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function to segregate even and odd nodes 
# and return the head of the new list.
def segregateEvenOdd(head):
  
    # Result list to hold even nodes
    resStart = None
    resEnd = None

    # Pointers for the original list
    curr = head
    prev = None

    # Move all even nodes from original to result
    while curr is not None:
      
        # If current node is even
        if curr.data % 2 == 0:
          
            # Remove the current even node from the original list
            if prev is not None:
                prev.next = curr.next
            else:
                # If the even node is at the head
                head = curr.next

            # Add the current even node to the result list
            if resStart is None:
                resStart = curr
                resEnd = resStart
            else:
                resEnd.next = curr
                resEnd = resEnd.next

            curr = curr.next
        else:
            # If the node is odd, just move to the next
            prev = curr
            curr = curr.next

    # If there are no even nodes, return the original list
    if resStart is None:
        return head

    # Append the remaining original list 
    # (odd nodes) to the result list
    resEnd.next = head

    # Return the result list (starting with even nodes)
    return resStart

# Function to print the linked list
def printList(node):
    while node is not None:
        print(node.data, end=" ")
        node = node.next
    print()

if __name__ == "__main__":
    # Create a sample linked list: 0->1->4->6->9->10->11
    head = Node(0)
    head.next = Node(1)
    head.next.next = Node(4)
    head.next.next.next = Node(6)
    head.next.next.next.next = Node(9)
    head.next.next.next.next.next = Node(10)
    head.next.next.next.next.next.next = Node(11)

    print("Original Linked list: ", end="")
    printList(head)

    head = segregateEvenOdd(head)

    print("Modified Linked list: ", end="")
    printList(head)
C#
using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to segregate even and odd nodes and 
    // return the head of the new list
    public static Node SegregateEvenOdd(Node head) {
      
        // Result list to hold even nodes
        Node resStart = null;
        Node resEnd = null;

        // Pointers for the original list
        Node curr = head;
        Node prev = null;

        // Move all even nodes from original to result
        while (curr != null) {
            // If current node is even
            if (curr.data % 2 == 0) {
              
                // Remove the current even node 
                // from the original list
                if (prev != null) {
                    prev.next = curr.next;
                } else {
                    // If the even node is at the head
                    head = curr.next;
                }

                // Add the current even node to the result list
                if (resStart == null) {
                    resStart = curr;
                    resEnd = resStart;
                } else {
                    resEnd.next = curr;
                    resEnd = resEnd.next;
                }

                curr = curr.next;
            } else {
                // If the node is odd, just move to the next
                prev = curr;
                curr = curr.next;
            }
        }

        // If there are no even nodes, return the original list
        if (resStart == null) {
            return head;
        }

        // Append the remaining original 
        // list (odd nodes) to the result list
        resEnd.next = head;

        // Return the result list (starting with even nodes)
        return resStart;
    }

    // Function to print the linked list
    public static void PrintList(Node node) {
        while (node != null) {
            Console.Write(node.data + " ");
            node = node.next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args) {
        // Create a sample linked list: 0->1->4->6->9->10->11
        Node head = new Node(0);
        head.next = new Node(1);
        head.next.next = new Node(4);
        head.next.next.next = new Node(6);
        head.next.next.next.next = new Node(9);
        head.next.next.next.next.next = new Node(10);
        head.next.next.next.next.next.next = new Node(11);

        Console.Write("Original Linked list: ");
        PrintList(head);

        head = SegregateEvenOdd(head);

        Console.Write("Modified Linked list: ");
        PrintList(head);
    }
}
JavaScript
class Node {
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
}

// Function to segregate even and odd nodes and return the
// head of the new list
function segregateEvenOdd(head)
{
    // Result list to hold even nodes
    let resStart = null;
    let resEnd = null;

    // Pointers for the original list
    let curr = head;
    let prev = null;

    // Move all even nodes from original to result
    while (curr !== null) {
    
        // If current node is even
        if (curr.data % 2 === 0) {
        
            // Remove the current even node from the
            // original list
            if (prev !== null) {
                prev.next = curr.next;
            }
            else {
                // If the even node is at the head
                head = curr.next;
            }

            // Add the current even node to the result list
            if (resStart === null) {
                resStart = curr;
                resEnd = resStart;
            }
            else {
                resEnd.next = curr;
                resEnd = resEnd.next;
            }

            curr = curr.next;
        }
        else {
            // If the node is odd, just move to the next
            prev = curr;
            curr = curr.next;
        }
    }

    // If there are no even nodes, return the original list
    if (resStart === null) {
        return head;
    }

    // Append the remaining original list (odd nodes) to the
    // result list
    resEnd.next = head;

    // Return the result list (starting with even nodes)
    return resStart;
}

// Function to print the linked list
function printList(node)
{
    let curr = node;
    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        curr = curr.next;
    }
    process.stdout.write("\n");
}

// Create a sample linked list: 0->1->4->6->9->10->11
let head = new Node(0);
head.next = new Node(1);
head.next.next = new Node(4);
head.next.next.next = new Node(6);
head.next.next.next.next = new Node(9);
head.next.next.next.next.next = new Node(10);
head.next.next.next.next.next.next = new Node(11);

process.stdout.write("Original Linked list: ");
printList(head);

head = segregateEvenOdd(head);

process.stdout.write("Modified Linked list: ");
printList(head);

Output
Original Linked list: 0 1 4 6 9 10 11 
Modified Linked list: 0 4 6 10 1 9 11 

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

Maintaining Start and End - O(n) Time and O(1) Space

The idea is to initialize pointers to track even and odd list separately. Traverse the list list end. While traversing the odd data node should be appended in odd list pointer and even data node should be appended in even list pointer and update the original list's head to the even list's head.

Step-by-step implementation:

  • 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.

Below is the implementation of the above approach. Note that we create dummy nodes to avoid extra condition checks in the while loop.

C++
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to segregate even and odd nodes 
// and return the head of the new list.
Node* segregateEvenOdd(Node* head) {
  
    // We create dummy nodes to avoid extra 
    // condition checks in the while loop.
    Node* eStart = new Node(0);
    Node* oStart = new Node(0);
    
    // Pointers to the end of the even and
    // odd lists
    Node* eEnd = eStart;
    Node* oEnd = oStart;

    // Node to traverse the list
    Node* curr = head;

    while (curr != nullptr) {
        int val = curr->data;

        // If current value is even, add it 
        // to the even list
        if (val % 2 == 0) {
            eEnd->next = curr;
            eEnd = eEnd->next;
        } else { // Else to the odd list
            oEnd->next = curr;
            oEnd = oEnd->next;
        }

        // Move to the next node
        curr = curr->next;
    }

    // Terminate the odd list
    oEnd->next = nullptr;

    // Combine even and odd lists
    eEnd->next = oStart->next;

    // Return the new head of the 
    // combined list (even head)
    Node* newHead = eStart->next;

    // Clean up starting dummy nodes
    delete eStart;
    delete oStart;

    return newHead;
}

void printList(Node* node) {
    while (node != nullptr) {
        cout << node->data << " ";
        node = node->next;
    }
}

int main() {
    // Let us create a sample linked list as following
    // 0->1->4->6->9->10->11
    Node* head = new Node(0);
    head->next = new Node(1);
    head->next->next = new Node(4);
    head->next->next->next = new Node(6);
    head->next->next->next->next = new Node(9);
    head->next->next->next->next->next = new Node(10);
    head->next->next->next->next->next->next = new Node(11);

    cout << "Original Linked list: ";
    printList(head);

    head = segregateEvenOdd(head);

    cout << "\nModified Linked list: ";
    printList(head);

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to create a new node
struct Node* newNode(int x) {
    struct Node* temp = 
      (struct Node*)malloc(sizeof(struct Node));
    temp->data = x;
    temp->next = NULL;
    return temp;
}

// Function to segregate even and odd nodes 
// and return the head of the new list.
struct Node* segregateEvenOdd(struct Node* head) {
  
    // We create dummy nodes to avoid extra 
    // condition checks in the while loop.
    struct Node* eStart = newNode(0);
    struct Node* oStart = newNode(0);
    
    // Pointers to the end of the even and odd lists
    struct Node* eEnd = eStart;
    struct Node* oEnd = oStart;

    // Node to traverse the list
    struct Node* curr = head;

    while (curr != NULL) {
        int val = curr->data;

        // If current value is even, add it to the even list
        if (val % 2 == 0) {
            eEnd->next = curr;
            eEnd = eEnd->next;
        } else { // Else to the odd list
            oEnd->next = curr;
            oEnd = oEnd->next;
        }

        // Move to the next node
        curr = curr->next;
    }

    // Terminate the odd list
    oEnd->next = NULL;

    // Combine even and odd lists
    eEnd->next = oStart->next;

    // Return the new head of the combined list (even head)
    struct Node* newHead = eStart->next;

    // Clean up dummy nodes
    free(eStart);
    free(oStart);

    return newHead;
}

// Function to print the linked list
void printList(struct Node* node) {
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}

int main() {
    // Let us create a sample linked list as following
    // 0->1->4->6->9->10->11
    struct Node* head = newNode(0);
    head->next = newNode(1);
    head->next->next = newNode(4);
    head->next->next->next = newNode(6);
    head->next->next->next->next = newNode(9);
    head->next->next->next->next->next = newNode(10);
    head->next->next->next->next->next->next = newNode(11);

    printf("Original Linked list: ");
    printList(head);

    head = segregateEvenOdd(head);

    printf("\nModified Linked list: ");
    printList(head);

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    // Function to segregate even and odd nodes
    // and return the head of the new list.
    public static Node segregateEvenOdd(Node head) {

        // We create dummy nodes to avoid extra 
        // condition checks in the while loop.
        Node eStart = new Node(0);
        Node oStart = new Node(0);

        // Pointers to the end of the even and odd lists
        Node eEnd = eStart;
        Node oEnd = oStart;

        // Node to traverse the list
        Node curr = head;

        while (curr != null) {
            int val = curr.data;

            // If current value is even, add it to the even list
            if (val % 2 == 0) {
                eEnd.next = curr;
                eEnd = eEnd.next;
            } else { // Else to the odd list
                oEnd.next = curr;
                oEnd = oEnd.next;
            }

            // Move to the next node
            curr = curr.next;
        }

        // Terminate the odd list
        oEnd.next = null;

        // Combine even and odd lists
        eEnd.next = oStart.next;

        // Return the new head of the combined list (even head)
        return eStart.next;
    }

    // Function to print the linked list
    public static void printList(Node node) {
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }

    public static void main(String[] args) {
        // Let us create a sample linked list as following
        // 0->1->4->6->9->10->11
        Node head = new Node(0);
        head.next = new Node(1);
        head.next.next = new Node(4);
        head.next.next.next = new Node(6);
        head.next.next.next.next = new Node(9);
        head.next.next.next.next.next = new Node(10);
        head.next.next.next.next.next.next = new Node(11);

        System.out.print("Original Linked list: ");
        printList(head);

        head = segregateEvenOdd(head);

        System.out.print("\nModified Linked list: ");
        printList(head);
    }
}
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# Function to segregate even and odd nodes
# and return the head of the new list.
def segregateEvenOdd(head):
  
    # We create dummy nodes to avoid extra 
    # condition checks in the while loop.
    eStart = Node(0)
    oStart = Node(0)

    # Pointers to the end of the even and odd lists
    eEnd = eStart
    oEnd = oStart

    # Node to traverse the list
    curr = head

    while curr:
        val = curr.data

        # If current value is even, add it to the even list
        if val % 2 == 0:
            eEnd.next = curr
            eEnd = eEnd.next
        else:  # Else to the odd list
            oEnd.next = curr
            oEnd = oEnd.next

        # Move to the next node
        curr = curr.next

    # Terminate the odd list
    oEnd.next = None

    # Combine even and odd lists
    eEnd.next = oStart.next

    # Return the new head of the combined list (even head)
    return eStart.next

# Function to print the linked list
def printList(node):
    while node:
        print(node.data, end=" ")
        node = node.next

if __name__ == "__main__":
    # Let us create a sample linked list as following
    # 0->1->4->6->9->10->11
    head = Node(0)
    head.next = Node(1)
    head.next.next = Node(4)
    head.next.next.next = Node(6)
    head.next.next.next.next = Node(9)
    head.next.next.next.next.next = Node(10)
    head.next.next.next.next.next.next = Node(11)

    print("Original Linked list: ", end="")
    printList(head)

    head = segregateEvenOdd(head)

    print("\nModified Linked list: ", end="")
    printList(head)
C#
using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to segregate even and odd nodes
    // and return the head of the new list.
    public static Node SegregateEvenOdd(Node head) {
        // We create dummy nodes to avoid extra 
        // condition checks in the while loop.
        Node eStart = new Node(0);
        Node oStart = new Node(0);

        // Pointers to the end of the even and odd lists
        Node eEnd = eStart;
        Node oEnd = oStart;

        // Node to traverse the list
        Node curr = head;

        while (curr != null) {
            int val = curr.data;

            // If current value is even, add it to the even list
            if (val % 2 == 0) {
                eEnd.next = curr;
                eEnd = eEnd.next;
            } else { // Else to the odd list
                oEnd.next = curr;
                oEnd = oEnd.next;
            }

            // Move to the next node
            curr = curr.next;
        }

        // Terminate the odd list
        oEnd.next = null;

        // Combine even and odd lists
        eEnd.next = oStart.next;

        // Return the new head of the combined list (even head)
        return eStart.next;
    }

    // Function to print the linked list
    public static void PrintList(Node node) {
        Node curr = node;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
    }

    public static void Main() {
        // Let us create a sample linked list as following
        // 0->1->4->6->9->10->11
        Node head = new Node(0);
        head.next = new Node(1);
        head.next.next = new Node(4);
        head.next.next.next = new Node(6);
        head.next.next.next.next = new Node(9);
        head.next.next.next.next.next = new Node(10);
        head.next.next.next.next.next.next = new Node(11);

        Console.Write("Original Linked list: ");
        PrintList(head);

        head = SegregateEvenOdd(head);

        Console.Write("\nModified Linked list: ");
        PrintList(head);
    }
}
JavaScript
class Node {
    constructor(data)
    {
        this.data = data;
        this.next = null;
    }
}

// Function to segregate even and odd nodes
// and return the head of the new list.
function segregateEvenOdd(head)
{

    // We create dummy nodes to avoid extra
    // condition checks in the while loop.
    let eStart = new Node(0);
    let oStart = new Node(0);

    // Pointers to the end of the even and odd lists
    let eEnd = eStart;
    let oEnd = oStart;

    // Node to traverse the list
    let curr = head;

    while (curr !== null) {
        let val = curr.data;

        // If current value is even, add it to the even list
        if (val % 2 === 0) {
            eEnd.next = curr;
            eEnd = eEnd.next;
        }
        else { // Else to the odd list
            oEnd.next = curr;
            oEnd = oEnd.next;
        }

        // Move to the next node
        curr = curr.next;
    }

    // Terminate the odd list
    oEnd.next = null;

    // Combine even and odd lists
    eEnd.next = oStart.next;

    // Return the new head of the combined list (even head)
    return eStart.next;
}

// Function to print the linked list
function printList(node)
{
    let curr = node;
    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        curr = curr.next;
    }
}

// Let us create a sample linked list as following
// 0->1->4->6->9->10->11
let head = new Node(0);
head.next = new Node(1);
head.next.next = new Node(4);
head.next.next.next = new Node(6);
head.next.next.next.next = new Node(9);
head.next.next.next.next.next = new Node(10);
head.next.next.next.next.next.next = new Node(11);

process.stdout.write("Original Linked list: ");
printList(head);

head = segregateEvenOdd(head);

process.stdout.write("\nModified Linked list: ");
printList(head);

Output
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).


Next Article
Article Tags :
Practice Tags :

Similar Reads