Sort a linked list of 0s, 1s and 2s
Last Updated :
26 Apr, 2025
Given a linked list where nodes can contain values 0s, 1s, and 2s only. The task is to sort 0s, 1s, 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
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.
Input: head: 2 → 2 → 0 → 1
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.
[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();
[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();
[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(" "));
[Expected Approach - 3] Using Dutch National Flag Algorithm - O(n) Time and O(1) Space
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();
Given a linked list of 0s, 1s and 2s, sort it | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem