Sort a linked list of 0s, 1s and 2s

Last Updated : 10 Oct, 2026

Given a head of linked list containing nodes with values 0, 1, and 2 only, rearrange the list so that all 0s appear first, followed by all 1s, and then all 2s at the end, while maintaining the relative order within each group.

Examples:

Input:

1

Output: 0 -> 1 ->1 ->2 ->2 -> 2 -> 2 -> 2
Explanation: All the 0s are segregated to the left end of the linked list, 2s to the right end of the list, and 1s in between.

2-

Input:

3-

Output: 0 ->1 -> 2 -> 2
Explanation: After arranging all the 0s, 1s and 2s in the given format, the output will be 0 -> 1 -> 2 -> 2.

4
Try It Yourself
redirect icon

Maintaining Frequency - O(n) Time and O(1) Space

The idea is to traverse the linked list and count the occurrences of 0, 1, and 2 using an array cnt[] of size 3. Then, traverse the list again and update the node values by placing all 0s first, followed by 1s and then 2s.

  • cnt[0] stores the count of nodes having value 0.
  • cnt[1] stores the count of nodes having value 1.
  • cnt[2] stores the count of nodes having value 2.
C++
#include <iostream>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int new_data)
    {
        data = new_data;
        next = nullptr;
    }
};

Node *segregate(Node *head)
{
    int cnt[3] = {0, 0, 0};
    Node *curr = head;

    // Count occurrences of 0, 1 and 2
    while (curr)
    {
        cnt[curr->data]++;
        curr = curr->next;
    }

    curr = head;
    int idx = 0;

    // Update node values in sorted order
    while (curr)
    {
        if (cnt[idx] == 0)
        {
            idx++;
        }
        else
        {
            curr->data = idx;
            cnt[idx]--;
            curr = curr->next;
        }
    }

    return head;
}

int main()
{

    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(2);
    head->next->next->next = new Node(1);
    head->next->next->next->next = new Node(2);
    head->next->next->next->next->next = new Node(0);
    head->next->next->next->next->next->next = new Node(2);
    head->next->next->next->next->next->next->next = new Node(2);

    head = segregate(head);

    while (head != nullptr)
    {
        cout << head->data;
        if (head->next != nullptr)
        {
            cout << " -> ";
        }
        head = head->next;
    }
    cout << "\n";
    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node next;

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

public class GFG {
    static Node segregate(Node head)
    {
        int[] cnt = { 0, 0, 0 };
        Node curr = head;

        // Count occurrences of 0, 1 and 2
        while (curr != null) {
            cnt[curr.data]++;
            curr = curr.next;
        }

        curr = head;
        int idx = 0;

        // Update node values in sorted order
        while (curr != null) {
            if (cnt[idx] == 0) {
                idx++;
            }
            else {
                curr.data = idx;
                cnt[idx]--;
                curr = curr.next;
            }
        }

        return head;
    }

    public static void main(String[] args)
    {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(1);
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.next = new Node(0);
        head.next.next.next.next.next.next = new Node(2);
        head.next.next.next.next.next.next.next
            = new Node(2);

        head = segregate(head);

        while (head != null) {
            System.out.print(head.data);
            if (head.next != null) {
                System.out.print(" -> ");
            }
            head = head.next;
        }
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

def segregate(head):
    cnt = [0, 0, 0]
    curr = head

    # Count occurrences of 0, 1 and 2
    while curr is not None:
        cnt[curr.data] += 1
        curr = curr.next

    curr = head
    idx = 0

    # Update node values in sorted order
    while curr is not None:
        if cnt[idx] == 0:
            idx += 1
        else:
            curr.data = idx
            cnt[idx] -= 1
            curr = curr.next

    return head

def printList(node):
    while node is not None:
        print(node.data, end=" -> " if node.next is not None else "\n")
        node = node.next

if __name__ == '__main__':
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(2)
    head.next.next.next = Node(1)
    head.next.next.next.next = Node(2)
    head.next.next.next.next.next = Node(0)
    head.next.next.next.next.next.next = Node(2)
    head.next.next.next.next.next.next.next = Node(2)

    head = segregate(head)
    printList(head)
C#
using System;

public class Node {
    public int data;
    public Node next;

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

public class GFG {
    static Node segregate(Node head)
    {
        int[] cnt = { 0, 0, 0 };
        Node curr = head;

        // Count occurrences of 0, 1 and 2
        while (curr != null) {
            cnt[curr.data]++;
            curr = curr.next;
        }

        curr = head;
        int idx = 0;

        // Update node values in sorted order
        while (curr != null) {
            if (cnt[idx] == 0) {
                idx++;
            }
            else {
                curr.data = idx;
                cnt[idx]--;
                curr = curr.next;
            }
        }

        return head;
    }

    static void Main()
    {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(1);
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.next = new Node(0);
        head.next.next.next.next.next.next = new Node(2);
        head.next.next.next.next.next.next.next
            = new Node(2);

        head = segregate(head);

        while (head != null) {
            Console.Write(head.data);
            if (head.next != null) {
                Console.Write(" -> ");
            }
            head = head.next;
        }
        Console.WriteLine();
    }
}
JavaScript
class Node {
    constructor(new_data)
    {
        this.data = new_data;
        this.next = null;
    }
}

function segregate(head)
{
    let cnt = [ 0, 0, 0 ];
    let curr = head;

    // Count occurrences of 0, 1 and 2
    while (curr !== null) {
        cnt[curr.data]++;
        curr = curr.next;
    }

    curr = head;
    let idx = 0;

    // Update node values in sorted order
    while (curr !== null) {
        if (cnt[idx] === 0) {
            idx++;
        }
        else {
            curr.data = idx;
            cnt[idx]--;
            curr = curr.next;
        }
    }

    return head;
}

function printList(node)
{
    while (node !== null) {
        process.stdout.write(node.data);
        if (node.next !== null) {
            process.stdout.write(" -> ");
        }
        node = node.next;
    }
    console.log();
}

// Driver Code
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(0);
head.next.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next.next = new Node(2);

head = segregate(head);

while (head) {
    process.stdout.write(String(head.data));

    if (head.next) {
        process.stdout.write(" -> ");
    }

    head = head.next;
}
console.log();

Output
0 -> 1 -> 1 -> 2 -> 2 -> 2 -> 2 -> 2

Changing Links of Nodes - O(n) Time and O(1) Space

The idea is to create three separate linked lists for nodes containing 0, 1, and 2, then connect these lists in the required order. This is mainly based on Dutch National Flag algorithm.

  • If the current node's value is 0, append it to the list of 0s and move the zero pointer to the current node.
  • If the current node's value is 1, append it to the list of 1s and move the one pointer to the current node.
  • If the current node's value is 2, append it to the list of 2s and move the two pointer to the current node.

Finally, connect the three lists in the order 0, 1, and 2. To avoid handling empty lists separately, use three dummy nodes, zeroD, oneD, and twoD, as the starting points of the lists.

C++
#include <iostream>
using namespace std;

class Node
{
  public:
    int data;
    Node *next;

    Node(int new_data)
    {
        data = new_data;
        next = nullptr;
    }
};

Node *segregate(Node *head)
{
    // Create dummy nodes for the three lists.
    Node zeroD(0), oneD(0), twoD(0);
    Node *zero = &zeroD, *one = &oneD, *two = &twoD;

    Node *curr = head;

    // Divide nodes into lists based on their values.
    while (curr)
    {
        Node *nextNode = curr->next;

        if (curr->data == 0)
        {
            zero->next = curr;
            zero = zero->next;
        }
        else if (curr->data == 1)
        {
            one->next = curr;
            one = one->next;
        }
        else
        {
            two->next = curr;
            two = two->next;
        }

        // Move to the next node in the original list.
        curr = nextNode;
    }

    // Connect the three lists in the order 0, 1, and 2.
    zero->next = oneD.next ? oneD.next : twoD.next;
    one->next = twoD.next;
    two->next = nullptr;

    // Return the head of the rearranged list.
    return zeroD.next;
}

int main()
{

    Node *head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(2);
    head->next->next->next = new Node(1);
    head->next->next->next->next = new Node(2);
    head->next->next->next->next->next = new Node(0);
    head->next->next->next->next->next->next = new Node(2);
    head->next->next->next->next->next->next->next = new Node(2);

    head = segregate(head);

    while (head != nullptr)
    {
        cout << head->data;
        if (head->next != nullptr)
        {
            cout << " -> ";
        }
        head = head->next;
    }
    cout << "\n";
    return 0;
}
Java
import java.util.*;

class Node {
    public int data;
    public Node next;

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

public class GFG {
    Node segregate(Node head)
    {
        // Create dummy nodes for the three lists.
        Node zeroD = new Node(0), oneD = new Node(0),
             twoD = new Node(0);
        Node zero = zeroD, one = oneD, two = twoD;

        Node curr = head;

        // Divide nodes into lists based on their values.
        while (curr != null) {
            Node nextNode = curr.next;

            if (curr.data == 0) {
                zero.next = curr;
                zero = zero.next;
            }
            else if (curr.data == 1) {
                one.next = curr;
                one = one.next;
            }
            else {
                two.next = curr;
                two = two.next;
            }

            // Move to the next node in the original list.
            curr = nextNode;
        }

        // Connect the three lists in the order 0, 1, and 2.
        zero.next
            = (oneD.next != null) ? oneD.next : twoD.next;
        one.next = twoD.next;
        two.next = null;

        // Return the head of the rearranged list.
        return zeroD.next;
    }

    public static void main(String[] args)
    {
        GFG main = new GFG();

        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(1);
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.next = new Node(0);
        head.next.next.next.next.next.next = new Node(2);
        head.next.next.next.next.next.next.next
            = new Node(2);

        head = main.segregate(head);

        while (head != null) {
            System.out.print(head.data);
            if (head.next != null) {
                System.out.print(" -> ");
            }
            head = head.next;
        }
        System.out.println();
    }
}
Python
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

def segregate(head):
    # Create dummy nodes for the three lists.
    zeroD = Node(0)
    oneD = Node(0)
    twoD = Node(0)
    zero = zeroD
    one = oneD
    two = twoD

    curr = head

    # Divide nodes into lists based on their values.
    while curr:
        nextNode = curr.next

        if curr.data == 0:
            zero.next = curr
            zero = zero.next
        elif curr.data == 1:
            one.next = curr
            one = one.next
        else:
            two.next = curr
            two = two.next

        # Move to the next node in the original list.
        curr = nextNode

    # Connect the three lists in the order 0, 1, and 2.
    zero.next = oneD.next if oneD.next else twoD.next
    one.next = twoD.next
    two.next = None

    # Return the head of the rearranged list.
    return zeroD.next

if __name__ == '__main__':
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(2)
    head.next.next.next = Node(1)
    head.next.next.next.next = Node(2)
    head.next.next.next.next.next = Node(0)
    head.next.next.next.next.next.next = Node(2)
    head.next.next.next.next.next.next.next = Node(2)

    head = segregate(head)

    while head:
        print(head.data, end='')
        if head.next:
            print(' -> ', end='')
        head = head.next
    print()
C#
using System;

public class Node {
    public int data;
    public Node next;

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

public class GFG {
    public Node segregate(Node head)
    {
        // Create dummy nodes for the three lists.
        Node zeroD = new Node(0), oneD = new Node(0),
             twoD = new Node(0);
        Node zero = zeroD, one = oneD, two = twoD;

        Node curr = head;

        // Divide nodes into lists based on their values.
        while (curr != null) {
            Node nextNode = curr.next;

            if (curr.data == 0) {
                zero.next = curr;
                zero = zero.next;
            }
            else if (curr.data == 1) {
                one.next = curr;
                one = one.next;
            }
            else {
                two.next = curr;
                two = two.next;
            }

            // Move to the next node in the original list.
            curr = nextNode;
        }

        // Connect the three lists in the order 0, 1, and 2.
        zero.next
            = oneD.next != null ? oneD.next : twoD.next;
        one.next = twoD.next;
        two.next = null;

        // Return the head of the rearranged list.
        return zeroD.next;
    }

    public static void Main()
    {
        GFG program = new GFG();

        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(1);
        head.next.next.next.next = new Node(2);
        head.next.next.next.next.next = new Node(0);
        head.next.next.next.next.next.next = new Node(2);
        head.next.next.next.next.next.next.next
            = new Node(2);

        head = program.segregate(head);

        while (head != null) {
            Console.Write(head.data);
            if (head.next != null)
                Console.Write(" -> ");
            head = head.next;
        }
        Console.WriteLine();
    }
}
JavaScript
class Node {
    constructor(new_data)
    {
        this.data = new_data;
        this.next = null;
    }
}

function segregate(head)
{
    // Create dummy nodes for the three lists.
    let zeroD = new Node(0), oneD = new Node(0),
        twoD = new Node(0);
    let zero = zeroD, one = oneD, two = twoD;

    let curr = head;

    // Divide nodes into lists based on their values.
    while (curr) {
        let nextNode = curr.next;

        if (curr.data === 0) {
            zero.next = curr;
            zero = zero.next;
        }
        else if (curr.data === 1) {
            one.next = curr;
            one = one.next;
        }
        else {
            two.next = curr;
            two = two.next;
        }

        // Move to the next node in the original list.
        curr = nextNode;
    }

    // Connect the three lists in the order 0, 1, and 2.
    zero.next = oneD.next ? oneD.next : twoD.next;
    one.next = twoD.next;
    two.next = null;

    // Return the head of the rearranged list.
    return zeroD.next;
}

// Driver Code
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(2);
head.next.next.next.next.next = new Node(0);
head.next.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next.next = new Node(2);

head = segregate(head);

while (head) {
    process.stdout.write(String(head.data));

    if (head.next) {
        process.stdout.write(" -> ");
    }

    head = head.next;
}
console.log();

Output
0 -> 1 -> 1 -> 2 -> 2 -> 2 -> 2 -> 2
Comment