Open In App

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

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list where nodes can contain values 0s1s, and 2s only. The task is to sort 0s1s, and 2s in the linked list such that all zeros segregate to the head side, 2s at the end of the linked list, and 1s in the middle of 0s and 2s.

Examples:

Input: head: 1 → 2 → 2 → 1 → 2 → 0 → 2 → 2

Sort-a-linked-list

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.

Sort-a-linked-list-of2

Input: head: 2 → 2 → 0 → 1

Sort-a-linked-list-of-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.

Sort-a-linked-list-of--4

[Naive Approach] Using an Extra Array – O(n*log(n)) Time and O(n) Space

The idea is to first convert the linked list into an array to easily leverage sorting, as sorting an array is straightforward and efficient. After sorting the array, we traverse the linked list again and reassign the sorted values back to the nodes.

C++
// C++ Program to sort a linked list 0s, 1s 
// or 2s by using an extra array
#include <bits/stdc++.h>
using namespace std;

// A linked list node
class Node {
public:
    int data;
    Node* next;

    // Constructor to initialize a new
    // node with data
    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Sort a linked list of 0s, 1s, and 2s 
// by using an extra array to store values
Node* segregate(Node* head) {
    if (!head || !(head->next)) 
        return head; 

    // Convert linked list to array
    vector<int> arr;
    Node* curr = head;
    while (curr) {
        arr.push_back(curr->data);
        curr = curr->next;
    }

    // Sort the array 
    sort(arr.begin(), arr.end());

    // Reassign sorted values back to the linked list
    curr = head;
    for (int i = 0; i < arr.size(); i++) {
        curr->data = arr[i];
        curr = curr->next;
    }

    return head; 
} 

// Driver code
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);
    
    // Function to sort the linked list (assuming it groups 0s, 1s, and 2s)
    head = segregate(head);

    // Print the sorted list
    while (head != nullptr) {
        cout << " " << head->data;
        head = head->next;
    }
    cout << "\n";
    return 0;
}
Java
// Java Program to sort a linked list 0s, 1s 
// or 2s by using an extra array
import java.util.*;

class Node {
    int data;
    Node next;

    // Constructor to initialize a new
    // node with data
    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

class GfG {

    // Sort a linked list of 0s, 1s, and 2s 
    // by using an extra array to store values
    static Node segregate(Node head) {
        if (head == null || head.next == null)
            return head;

        // Convert linked list to array
        ArrayList<Integer> arr = new ArrayList<>();
        Node curr = head;
        while (curr != null) {
            arr.add(curr.data);
            curr = curr.next;
        }

        // Sort the array 
        Collections.sort(arr);

        // Reassign sorted values back to the linked list
        curr = head;
        for (int i = 0; i < arr.size(); i++) {
            curr.data = arr.get(i);
            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);

        // Print the sorted list
        while (head != null) {
            System.out.print(" " + head.data);
            head = head.next;
        }
        System.out.println();
    }
}
Python
# Python Program to sort a linked list 0s, 1s 
# or 2s by using an extra array

# A linked list node
class Node:
    def __init__(self, new_data):
        
        # Constructor to initialize a new
        # node with data
        self.data = new_data
        self.next = None

# Sort a linked list of 0s, 1s, and 2s 
# by using an extra array to store values
def segregate(head):
    if not head or not head.next:
        return head

    # Convert linked list to array
    arr = []
    curr = head
    while curr:
        arr.append(curr.data)
        curr = curr.next

    # Sort the array 
    arr.sort()

    # Reassign sorted values back to the linked list
    curr = head
    for i in range(len(arr)):
        curr.data = arr[i]
        curr = curr.next

    return head

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)

    # Print the sorted list
    while head:
        print(" " + str(head.data), end="")
        head = head.next
    print()
C#
// C# Program to sort a linked list 0s, 1s 
// or 2s by using an extra array
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;

    // Constructor to initialize a new
    // node with data
    public Node(int new_data) {
        data = new_data;
        next = null;
    }
}

class GfG {

    // Sort a linked list of 0s, 1s, and 2s 
    // by using an extra array to store values
    public static Node segregate(Node head) {
        if (head == null || head.next == null)
            return head;

        // Convert linked list to array
        List<int> arr = new List<int>();
        Node curr = head;
        while (curr != null) {
            arr.Add(curr.data);
            curr = curr.next;
        }

        // Sort the array 
        arr.Sort();

        // Reassign sorted values back to the linked list
        curr = head;
        for (int i = 0; i < arr.Count; i++) {
            curr.data = arr[i];
            curr = curr.next;
        }

        return head;
    }

    public 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);

        // Print the sorted list
        while (head != null) {
            Console.Write(" " + head.data);
            head = head.next;
        }
        Console.WriteLine();
    }
}
JavaScript
// Javascript Program to sort a linked list 0s, 1s 
// or 2s by using an extra array

// A linked list node
class Node {
    constructor(new_data) {
        
        // Constructor to initialize a new
        // node with data
        this.data = new_data;
        this.next = null;
    }
}

// Sort a linked list of 0s, 1s, and 2s 
// by using an extra array to store values
function segregate(head) {
    if (!head || !head.next)
        return head;

    // Convert linked list to array
    let arr = [];
    let curr = head;
    while (curr) {
        arr.push(curr.data);
        curr = curr.next;
    }

    // Sort the array 
    arr.sort((a, b) => a - b);

    // Reassign sorted values back to the linked list
    curr = head;
    for (let i = 0; i < arr.length; i++) {
        curr.data = arr[i];
        curr = curr.next;
    }

    return head;
}

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);

// Print the sorted list
while (head) {
    process.stdout.write(" " + head.data);
    head = head.next;
}
console.log();

Output
 0 1 1 2 2 2 2 2

[Expected Approach – 1] Using Count of 0s, 1s and 2s – O(n) Time and O(1) Space

The idea is to traverse the linked list once and count the number of occurrences of 0s, 1s, and 2s. Once the counts are known, the linked list is traversed again, and the nodes are assigned the appropriate values based on the counts. First setting all nodes to 0, then to 1, and finally to 2.

C++
// C++ Program to sort a linked list 0s, 1s 
// or 2s by using count of 0s, 1s and 2s
#include <bits/stdc++.h>
using namespace std;

// A linked list node
class Node {
public:
    int data;
    Node* next;

    // Constructor to initialize a new
    // node with data
    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Sort a linked list of 0s, 1s and 2s 
// by updating pointers using counts
Node* segregate(Node* head) {
    if (!head || !(head->next)) 
        return head; 

    // Initialize counts for 0s, 1s, and 2s
    int cntZero = 0, cntOne = 0, cntTwo = 0;

    // Traverse the list to count the occurrences of 0, 1, and 2
    Node* curr = head;
    while (curr) {
        if (curr->data == 0) {
            cntZero++;
        } else if (curr->data == 1) {
            cntOne++;
        } else {
            cntTwo++;
        }
        curr = curr->next;
    }

    // Rebuild the list with sorted values
    curr = head;
    
    // First add all the 0s
    while (cntZero--) {
        curr->data = 0;
        curr = curr->next;
    }

    // Then add all the 1s
    while (cntOne--) {
        curr->data = 1;
        curr = curr->next;
    }

    // Finally add all the 2s
    while (cntTwo--) {
        curr->data = 2;
        curr = curr->next;
    }

    return head; 
} 

// Driver code
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);

    // Print the sorted list
    while (head != nullptr) {
        cout << " " << head->data;
        head = head->next;
    }
    cout << "\n";
    return 0;
}
Java
// Java Program to sort a linked list 0s, 1s 
// or 2s by using count of 0s, 1s and 2s
import java.util.*;

class Node {
    int data;
    Node next;

    // Constructor to initialize a new
    // node with data
    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

class GfG {

    // Sort a linked list of 0s, 1s and 2s 
    // by updating pointers using counts
    static Node segregate(Node head) {
        if (head == null || head.next == null)
            return head;

        // Initialize counts for 0s, 1s, and 2s
        int cntZero = 0, cntOne = 0, cntTwo = 0;

        // Traverse the list to count the 
        // occurrences of 0, 1, and 2
        Node curr = head;
        while (curr != null) {
            if (curr.data == 0) {
                cntZero++;
            } else if (curr.data == 1) {
                cntOne++;
            } else {
                cntTwo++;
            }
            curr = curr.next;
        }

        // Rebuild the list with sorted values
        curr = head;

        // First add all the 0s
        while (cntZero-- > 0) {
            curr.data = 0;
            curr = curr.next;
        }

        // Then add all the 1s
        while (cntOne-- > 0) {
            curr.data = 1;
            curr = curr.next;
        }

        // Finally add all the 2s
        while (cntTwo-- > 0) {
            curr.data = 2;
            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);

        // Print the sorted list
        while (head != null) {
            System.out.print(" " + head.data);
            head = head.next;
        }
        System.out.println();
    }
}
Python
# Python Program to sort a linked list 0s, 1s 
# or 2s by using count of 0s, 1s and 2s

# A linked list node
class Node:
    def __init__(self, new_data):
        # Constructor to initialize a new
        # node with data
        self.data = new_data
        self.next = None

# Sort a linked list of 0s, 1s and 2s 
# by updating pointers using counts
def segregate(head):
    if not head or not head.next:
        return head

    # Initialize counts for 0s, 1s, and 2s
    cntZero = 0
    cntOne = 0
    cntTwo = 0

    # Traverse the list to count the occurrences of 0, 1, and 2
    curr = head
    while curr:
        if curr.data == 0:
            cntZero += 1
        elif curr.data == 1:
            cntOne += 1
        else:
            cntTwo += 1
        curr = curr.next

    # Rebuild the list with sorted values
    curr = head

    # First add all the 0s
    while cntZero:
        curr.data = 0
        curr = curr.next
        cntZero -= 1

    # Then add all the 1s
    while cntOne:
        curr.data = 1
        curr = curr.next
        cntOne -= 1

    # Finally add all the 2s
    while cntTwo:
        curr.data = 2
        curr = curr.next
        cntTwo -= 1

    return head

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)

    # Print the sorted list
    while head:
        print(" " + str(head.data), end="")
        head = head.next
    print()
C#
// C# Program to sort a linked list 0s, 1s 
// or 2s by using count of 0s, 1s and 2s
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;

    // Constructor to initialize a new
    // node with data
    public Node(int new_data) {
        data = new_data;
        next = null;
    }
}

class GfG {

    // Sort a linked list of 0s, 1s and 2s 
    // by updating pointers using counts
    public static Node segregate(Node head) {
        if (head == null || head.next == null)
            return head;

        // Initialize counts for 0s, 1s, and 2s
        int cntZero = 0, cntOne = 0, cntTwo = 0;

        // Traverse the list to count the occurrences of 0, 1, and 2
        Node curr = head;
        while (curr != null) {
            if (curr.data == 0) {
                cntZero++;
            } else if (curr.data == 1) {
                cntOne++;
            } else {
                cntTwo++;
            }
            curr = curr.next;
        }

        // Rebuild the list with sorted values
        curr = head;

        // First add all the 0s
        while (cntZero-- > 0) {
            curr.data = 0;
            curr = curr.next;
        }

        // Then add all the 1s
        while (cntOne-- > 0) {
            curr.data = 1;
            curr = curr.next;
        }

        // Finally add all the 2s
        while (cntTwo-- > 0) {
            curr.data = 2;
            curr = curr.next;
        }

        return head;
    }

    public 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);

        // Print the sorted list
        while (head != null) {
            Console.Write(" " + head.data);
            head = head.next;
        }
        Console.WriteLine();
    }
}
JavaScript
// Javascript Program to sort a linked list 0s, 1s 
// or 2s by using count of 0s, 1s and 2s

// A linked list node
class Node {
    constructor(new_data) {
        // Constructor to initialize a new
        // node with data
        this.data = new_data;
        this.next = null;
    }
}

// Sort a linked list of 0s, 1s and 2s 
// by updating pointers using counts
function segregate(head) {
    if (!head || !head.next)
        return head;

    // Initialize counts for 0s, 1s, and 2s
    let cntZero = 0, cntOne = 0, cntTwo = 0;

    // Traverse the list to count the occurrences of 0, 1, and 2
    let curr = head;
    while (curr) {
        if (curr.data === 0) {
            cntZero++;
        } else if (curr.data === 1) {
            cntOne++;
        } else {
            cntTwo++;
        }
        curr = curr.next;
    }

    // Rebuild the list with sorted values
    curr = head;

    // First add all the 0s
    while (cntZero--) {
        curr.data = 0;
        curr = curr.next;
    }

    // Then add all the 1s
    while (cntOne--) {
        curr.data = 1;
        curr = curr.next;
    }

    // Finally add all the 2s
    while (cntTwo--) {
        curr.data = 2;
        curr = curr.next;
    }

    return head;
}

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);

// Print the sorted list
while (head) {
    process.stdout.write(" " + head.data);
    head = head.next;
}
console.log();

Output
 0 1 1 2 2 2 2 2

[Expected Approach – 2] By Changing Links of Nodes – O(n) Time and O(1) Space

The idea is to maintain 3 pointers named zero, one and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list.

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

Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as dummy headers of three lists.

C++
// C++ Program to sort a linked list 0s, 1s 
// or 2s by changing links of nodes
#include <bits/stdc++.h> 
using namespace std;

// A linked list node
class Node {
public:
    int data;
    Node* next;

    // Constructor to initialize a new
    // node with data
    Node(int new_data) {
        data = new_data;
        next = nullptr;
    }
};

// Sort a linked list of 0s, 1s and 2s 
// by changing pointers 
Node* segregate(Node* head) {
	if (!head || !(head->next)) 
		return head; 

	// Create three dummy nodes to point to beginning of 
	// three linked lists. These dummy nodes are created to 
	// avoid null checks. 
	Node* zeroD = new Node(0); 
	Node* oneD = new Node(0); 
	Node* twoD = new Node(0);

	// Initialize current pointers for three 
	// lists 
	Node *zero = zeroD, *one = oneD, *two = twoD; 

	// Traverse list 
	Node* curr = head; 
	while (curr) { 
		if (curr->data == 0) { 
          	
          	// If the data of current node is 0, 
      		// append it to pointer zero and update zero
			zero->next = curr; 
			zero = zero->next; 
		} 
		else if (curr->data == 1) { 
          	
          	// If the data of current node is 1, 
      		// append it to pointer one and update one
			one->next = curr; 
			one = one->next; 
		} 
		else { 
          	// If the data of current node is 2, 
      		// append it to pointer two and update two
			two->next = curr; 
			two = two->next; 
		} 
		curr = curr->next; 
	} 

	// Combine the three lists
	zero->next = (oneD->next) ? (oneD->next) : (twoD->next); 
	one->next = twoD->next; 
	two->next = NULL; 
  	
	// Updated head 
	head = zeroD->next; 

	// Delete dummy nodes 
	delete zeroD; 
	delete oneD; 
	delete twoD; 

	return head; 
} 

// Driver code
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);

    // Print the sorted list
    while (head != nullptr) {
        cout << " " << head->data;
        head = head->next;
    }
  	cout << "\n";
    return 0;
}
Java
// Java Program to sort a linked list of 0s, 1s 
// or 2s by changing links of nodes

// A linked list node
class Node {
    int data;
    Node next;

    // Constructor to initialize a new
    // node with data
    Node(int new_data) {
        data = new_data;
        next = null;
    }
}
 
class GfG {
    
  	// Sort a linked list of 0s, 1s and 2s 
	// by changing pointers
    static Node segregate(Node head) {
        if (head == null || head.next == null) 
            return head; 

        // Create three dummy nodes to point to beginning of 
        // three linked lists. These dummy nodes are created to 
        // avoid null checks. 
        Node zeroD = new Node(0); 
        Node oneD = new Node(0); 
        Node twoD = new Node(0);

        // Initialize current pointers for three 
        // lists 
        Node zero = zeroD, one = oneD, two = twoD; 

        // Traverse list 
        Node curr = head; 
        while (curr != null) { 
            if (curr.data == 0) { 
              	
                // If the data of current node is 0, 
                // append it to pointer zero and update zero
                zero.next = curr; 
                zero = zero.next; 
            } 
            else if (curr.data == 1) { 
              	
                // If the data of current node is 1, 
                // append it to pointer one and update one
                one.next = curr; 
                one = one.next; 
            } 
            else { 
              	
                // If the data of current node is 2, 
                // append it to pointer two and update two
                two.next = curr; 
                two = two.next; 
            } 
            curr = curr.next; 
        } 

        // Combine the three lists
        zero.next = (oneD.next != null) ? (oneD.next) : (twoD.next); 
        one.next = twoD.next; 
        two.next = null; 
          
        // Updated head 
        head = zeroD.next; 

        return head; 
    } 

  	// Driver code
    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);
            head = head.next;
        }
        System.out.println();
    }

}
Python
# Python Program to sort a linked list 0s, 1s 
# or 2s by changing links of nodes

# A linked list node
class Node:
  
  	# Constructor to initialize a new node with data
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Sort a linked list of 0s, 1s and 2s 
# by changing pointers 
def segregate(head):
    if not head or not head.next:
        return head

    # Create three dummy nodes to point to beginning of 
    # three linked lists. These dummy nodes are created to 
    # avoid null checks. 
    zeroD = Node(0)
    oneD = Node(0)
    twoD = Node(0)

    # Initialize current pointers for three 
    # lists 
    zero = zeroD
    one = oneD
    two = twoD

    # Traverse list 
    curr = head
    while curr:
        if curr.data == 0:
            # If the data of current node is 0, 
            # append it to pointer zero and update zero
            zero.next = curr
            zero = zero.next
        elif curr.data == 1:
            # If the data of current node is 1, 
            # append it to pointer one and update one
            one.next = curr
            one = one.next
        else:
            # If the data of current node is 2, 
            # append it to pointer two and update two
            two.next = curr
            two = two.next
        curr = curr.next

    # Combine the three lists
    zero.next = oneD.next if oneD.next else twoD.next
    one.next = twoD.next
    two.next = None

    # Updated head 
    head = zeroD.next

    return head

# Driver code
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 is not None:
        print(head.data, end=' ')
        head = head.next
    print()
    
C#
// C# Program to sort a linked list 0s, 1s 
// or 2s by changing links of nodes 
using System;

// A linked list node
public class Node {
    
    public int Data;
    public Node Next;

    // Constructor to initialize a new node with data
    public Node(int newData) {
        Data = newData;
        Next = null;
    }
}

// Sort a linked list of 0s, 1s and 2s 
// by changing pointers 
public class GfG {
    public static Node segregate(Node head) {
        if (head == null || head.Next == null)
            return head;

        // Create three dummy nodes to point to beginning of 
        // three linked lists. These dummy nodes are created to 
        // avoid null checks. 
        Node zeroD = new Node(0);
        Node oneD = new Node(0);
        Node twoD = new Node(0);

        // Initialize current pointers for three 
        // lists 
        Node zero = zeroD, one = oneD, two = twoD;

        // Traverse list 
        Node curr = head;
        while (curr != null) {
            if (curr.Data == 0) {
              
                // If the data of current node is 0, 
                // append it to pointer zero and update zero
                zero.Next = curr;
                zero = zero.Next;
            }
            else if (curr.Data == 1) {
              
                // If the data of current node is 1, 
                // append it to pointer one and update one
                one.Next = curr;
                one = one.Next;
            }
            else {
              
                // If the data of current node is 2, 
                // append it to pointer two and update two
                two.Next = curr;
                two = two.Next;
            }
            curr = curr.Next;
        }

        // Combine the three lists
        zero.Next = (oneD.Next != null) ? (oneD.Next) : (twoD.Next);
        one.Next = twoD.Next;
        two.Next = null;

        // Updated head 
        head = zeroD.Next;

        // Delete dummy nodes
        // In C# garbage collection will handle this

        return head;
    }

  	// Driver code
  	public 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);
        
        // Function to sort the linked list
        head = segregate(head);
        
        while (head != null) {
            Console.Write(" " + head.Data);
            head = head.Next;
        }
        Console.WriteLine();
        
    }
}
JavaScript
// Javascript program to sort a linked list of 0s, 1s 
// or 2s by changing links of nodes 

// A linked list node
class Node {
	
	// Constructor to initialize a new node with data
    constructor(newData) {
        this.data = newData;
        this.next = null;
    }
}

// Sort a linked list of 0s, 1s and 2s 
// by changing pointers 
function segregate(head) {
    if (!head || !head.next) 
        return head; 

    // Create three dummy nodes to point to beginning of 
    // three linked lists. These dummy nodes are created to 
    // avoid null checks. 
    let zeroD = new Node(0); 
    let oneD = new Node(0); 
    let twoD = new Node(0);

    // Initialize current pointers for three 
    // lists 
    let zero = zeroD, one = oneD, two = twoD; 

    // Traverse list 
    let curr = head; 
    while (curr) { 
        if (curr.data === 0) { 
        	
            // If the data of current node is 0, 
            // append it to pointer zero and update zero
            zero.next = curr; 
            zero = zero.next; 
        } 
        else if (curr.data === 1) { 
        	
            // If the data of current node is 1, 
            // append it to pointer one and update one
            one.next = curr; 
            one = one.next; 
        } 
        else { 
        	
            // If the data of current node is 2, 
            // append it to pointer two and update two
            two.next = curr; 
            two = two.next; 
        } 
        curr = curr.next; 
    } 

    // Combine the three lists
    zero.next = (oneD.next) ? (oneD.next) : (twoD.next); 
    one.next = twoD.next; 
    two.next = null; 

    // Updated head 
    head = zeroD.next; 

    // Delete dummy nodes 
    // In JavaScript, garbage collection will handle this

    return head; 
} 

// 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);

// Function to sort the linked list
head = segregate(head);
let result = [];
while (head !== null) {
    result.push(head.data);
    head = head.next;
}
console.log(result.join(" "));

Output
 0 1 1 2 2 2 2 2

The idea is to split the linked list into three separate sublists for 0s, 1s, and 2s using the Dutch National Flag algorithm. We maintain three dummy nodes and corresponding tail pointers to build each sublist during a single traversal. Once the segregation is done, we link these sublists in order: 0s -> 1s -> 2s. This avoids modifying node values and performs the operation in linear time and space.

Steps to implement the above idea:

  • Create three dummy nodes to act as the start of separate lists for 0s, 1s, and 2s.
  • Initialize three tail pointers (zero, one, two) that point to the end of each of these sublists.
  • Traverse the original list and based on node value, append it to the respective sublist using tail pointers.
  • After appending a node, move the corresponding tail pointer forward to keep track of the last node.
  • Once traversal is complete, link zero list to one list and then link one list to two list carefully.
  • Ensure the last node of two list points to NULL to terminate the final merged list correctly.
  • Return the head of the combined list which starts from the next of zero dummy node.
C++
// C++ Program to sort a linked list 0s, 1s 
// or 2s using Dutch National Flag Algorithm
#include <bits/stdc++.h>
using namespace std;

// A linked list node
class Node {
public:
    int data;
    Node* next;

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

// Sort a linked list of 0s, 1s and 2s 
// using Dutch National Flag logic (1-pass)
Node* segregate(Node* head) {
    if (!head || !(head->next)) {
        return head;
    }

    // Dummy nodes for three separate lists
    Node* zeroD = new Node(-1);
    Node* oneD = new Node(-1);
    Node* twoD = new Node(-1);

    // Tails for the three lists
    Node* zero = zeroD;
    Node* one = oneD;
    Node* two = twoD;

    // Traverse the original list
    Node* curr = head;
    while (curr) {
        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;
        }
        curr = curr->next;
    }

    // Connect the three lists together
    zero->next = oneD->next ? oneD->next : twoD->next;
    one->next = twoD->next;
    two->next = nullptr;

    // New head
    head = zeroD->next;

    // Delete dummy nodes
    delete zeroD;
    delete oneD;
    delete twoD;

    return head;
}

// Driver code
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);

    // Print the sorted list
    while (head != nullptr) {
        cout << " " << head->data;
        head = head->next;
    }
    cout << "\n";
    return 0;
}
Java
// Java Program to sort a linked list 0s, 1s 
// or 2s using Dutch National Flag Algorithm

class Node {
    int data;
    Node next;

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

class GfG {

    // Sort a linked list of 0s, 1s and 2s 
    // using Dutch National Flag logic (1-pass)
    static Node segregate(Node head) {
        if (head == null || head.next == null) {
            return head;
        }

        // Dummy nodes for three separate lists
        Node zeroD = new Node(-1);
        Node oneD = new Node(-1);
        Node twoD = new Node(-1);

        // Tails for the three lists
        Node zero = zeroD;
        Node one = oneD;
        Node two = twoD;

        // Traverse the original list
        Node curr = head;
        while (curr != null) {
            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;
            }
            curr = curr.next;
        }

        // Connect the three lists together
        zero.next = (oneD.next != null) ? oneD.next : twoD.next;
        one.next = twoD.next;
        two.next = null;

        // New head
        head = zeroD.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);

        // Print the sorted list
        while (head != null) {
            System.out.print(" " + head.data);
            head = head.next;
        }
        System.out.println();
    }
}
Python
# Python Program to sort a linked list 0s, 1s 
# or 2s using Dutch National Flag Algorithm

class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Sort a linked list of 0s, 1s and 2s 
# using Dutch National Flag logic (1-pass)
def segregate(head):
    if not head or not head.next:
        return head

    # Dummy nodes for three separate lists
    zeroD = Node(-1)
    oneD = Node(-1)
    twoD = Node(-1)

    # Tails for the three lists
    zero = zeroD
    one = oneD
    two = twoD

    # Traverse the original list
    curr = head
    while curr:
        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
        curr = curr.next

    # Connect the three lists together
    zero.next = oneD.next if oneD.next else twoD.next
    one.next = twoD.next
    two.next = None

    # New head
    head = zeroD.next

    return head

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)

    # Print the sorted list
    while head:
        print(" " + str(head.data), end="")
        head = head.next
    print()
C#
// C# Program to sort a linked list 0s, 1s 
// or 2s using Dutch National Flag Algorithm
using System;

class Node {
    public int data;
    public Node next;

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

class GfG {

    // Sort a linked list of 0s, 1s and 2s 
    // using Dutch National Flag logic (1-pass)
    public static Node segregate(Node head) {
        if (head == null || head.next == null) {
            return head;
        }

        // Dummy nodes for three separate lists
        Node zeroD = new Node(-1);
        Node oneD = new Node(-1);
        Node twoD = new Node(-1);

        // Tails for the three lists
        Node zero = zeroD;
        Node one = oneD;
        Node two = twoD;

        // Traverse the original list
        Node curr = head;
        while (curr != null) {
            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;
            }
            curr = curr.next;
        }

        // Connect the three lists together
        zero.next = (oneD.next != null) ? oneD.next : twoD.next;
        one.next = twoD.next;
        two.next = null;

        // New head
        head = zeroD.next;

        return head;
    }

    public 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);

        // Print the sorted list
        while (head != null) {
            Console.Write(" " + head.data);
            head = head.next;
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript Program to sort a linked list 0s, 1s 
// or 2s using Dutch National Flag Algorithm

function Node(new_data) {
    this.data = new_data;
    this.next = null;
}

// Sort a linked list of 0s, 1s and 2s 
// using Dutch National Flag logic (1-pass)
function segregate(head) {
    if (!head || !head.next) {
        return head;
    }

    // Dummy nodes for three separate lists
    let zeroD = new Node(-1);
    let oneD = new Node(-1);
    let twoD = new Node(-1);

    // Tails for the three lists
    let zero = zeroD;
    let one = oneD;
    let two = twoD;

    // Traverse the original list
    let curr = head;
    while (curr) {
        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;
        }
        curr = curr.next;
    }

    // Connect the three lists together
    zero.next = oneD.next ? oneD.next : twoD.next;
    one.next = twoD.next;
    two.next = null;

    // New head
    head = zeroD.next;

    return head;
}

// 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);

// Print the sorted list
while (head) {
    process.stdout.write(" " + head.data);
    head = head.next;
}
console.log();

Output
 0 1 1 2 2 2 2 2




Next Article

Similar Reads