#include <iostream>
using namespace std;
// Node class definition
class Node {
public:
int data;
Node* next;
Node(int x) : data(x), next(nullptr) {}
};
class Solution {
public:
Node* segregate(Node* head) {
if (!head || !head->next) return head;
// Count occurrences of 0s, 1s, and 2s
int cnt0 = 0, cnt1 = 0, cnt2 = 0;
Node* tmp = head;
while (tmp) {
if (tmp->data == 0) cnt0++;
else if (tmp->data == 1) cnt1++;
else if (tmp->data == 2) cnt2++;
tmp = tmp->next;
}
// Overwrite the list with sorted values
tmp = head;
while (cnt0--) { tmp->data = 0; tmp = tmp->next; }
while (cnt1--) { tmp->data = 1; tmp = tmp->next; }
while (cnt2--) { tmp->data = 2; tmp = tmp->next; }
return head;
}
};
// Helper function to create a linked list from an array
Node* createList(int arr[], int n) {
if (n == 0) return nullptr;
Node* head = new Node(arr[0]);
Node* current = head;
for (int i = 1; i < n; i++) {
current->next = new Node(arr[i]);
current = current->next;
}
return head;
}
// Helper function to print the linked list
void printList(Node* head) {
Node* current = head;
while (current) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
// Helper function to delete the linked list
void deleteList(Node* head) {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
int main() {
Solution sol;
// Test Case 1: Mixed 0s, 1s, and 2s
int arr1[] = {1, 2, 0, 1, 2, 0};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
Node* head1 = createList(arr1, n1);
cout << "Original List 1: ";
printList(head1);
head1 = sol.segregate(head1);
cout << "Sorted List 1: ";
printList(head1);
deleteList(head1);
// Test Case 2: All 0s
int arr2[] = {0, 0, 0};
int n2 = sizeof(arr2)/sizeof(arr2[0]);
Node* head2 = createList(arr2, n2);
cout << "Original List 2: ";
printList(head2);
head2 = sol.segregate(head2);
cout << "Sorted List 2: ";
printList(head2);
deleteList(head2);
// Test Case 3: Already sorted
int arr3[] = {0, 0, 1, 1, 2, 2};
int n3 = sizeof(arr3)/sizeof(arr3[0]);
Node* head3 = createList(arr3, n3);
cout << "Original List 3: ";
printList(head3);
head3 = sol.segregate(head3);
cout << "Sorted List 3: ";
printList(head3);
deleteList(head3);
// Test Case 4: Single element
int arr4[] = {1};
int n4 = sizeof(arr4)/sizeof(arr4[0]);
Node* head4 = createList(arr4, n4);
cout << "Original List 4: ";
printList(head4);
head4 = sol.segregate(head4);
cout << "Sorted List 4: ";
printList(head4);
deleteList(head4);
// Test Case 5: Empty list
Node* head5 = nullptr;
cout << "Original List 5: ";
printList(head5);
head5 = sol.segregate(head5);
cout << "Sorted List 5: ";
printList(head5);
deleteList(head5);
return 0;
}