Home » Technical Interview Questions » LinkedList Interview Questions » Sort a linked list with 0s, 1s and 2s

# Sort a linked list with 0s, 1s and 2s

## In the given linked list, which contains only 0s, 1s or 2s. Write a function to sort the linked list.

### Example Time complexity : O(n)

## Algorithm

a. Create a count array of size 3,

count stores count of 0
count stores count of 1
count stores count of 2

b. Traverse in the linked list count the number of 0s, 1s and 2s. Let counts be c0, c1 and c2.

c. Traverse the linked list again and fill it with 0s first c0 nodes, 1s with next c1 nodes and last c2 nodes with 2s.

### Algorithm working ## C++ Program

```#include <bits/stdc++.h>

using namespace std;

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

{
//count array to store count of 0s, 1s and 2s
//temp is pointer to traverse in the array
int count = {0, 0, 0};
while (temp != NULL)
{
count[temp->data] += 1;
temp = temp->next;
}
//Traverse in the array and fill with 0s, 1s and 2s
//first count places with 0s
//second count places with 1s
//last count places with 2s
int i = 0;
while (temp != NULL)
{
if (count[i] == 0)
{
i = i + 1;
}
else
{
temp->data = i;
count[i] = count[i] - 1 ;
temp = temp->next;
}
}
}

/* Function to insertAtBeginning a node */
void insertAtBeginning(struct LLNode** head, int dataToBeInserted)
{
struct LLNode* curr = new LLNode;
curr->data = dataToBeInserted;
curr->next = NULL;
*head=curr; //if this is first node make this as head of list

else
{
curr->next=*head; //else make the curr (new) node's next point to head and make this new node a the head
}

//O(1) constant time
}

void display(struct LLNode**node)
{
struct LLNode *temp= *node;
while(temp!=NULL)
{
if(temp->next!=NULL)
cout<<temp->data<<" ->";
else
cout<<temp->data;

temp=temp->next; //move to next node
}
//O(number of nodes)
cout<<endl;
}

//Main function
int main(void)
{