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

Given a linked list of 0s, 1s and 2s, sort it.

Source: Microsoft Interview | Set 1

## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Following steps can be used to sort the given linked list.
1) Traverse the list and count the number of 0s, 1s and 2s. Let the counts be n1, n2 and n3 respectively.
2) Traverse the list again, fill the first n1 nodes with 0, then n2 nodes with 1 and finally n3 nodes with 2.

## C/C++

```// C Program to sort a linked list 0s, 1s or 2s
#include<stdio.h>
#include<stdlib.h>

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

// Function to sort a linked list of 0s, 1s and 2s
{
int count[3] = {0, 0, 0};  // Initialize count of '0', '1' and '2' as 0

/* count total number of '0', '1' and '2'
* count[0] will store total number of '0's
* count[1] will store total number of '1's
* count[2] will store total number of '2's  */
while (ptr != NULL)
{
count[ptr->data] += 1;
ptr = ptr->next;
}

int i = 0;

/* Let say count[0] = n1, count[1] = n2 and count[2] = n3
* now start traversing list from head node,
* 1) fill the list with 0, till n1 > 0
* 2) fill the list with 1, till n2 > 0
* 3) fill the list with 2, till n3 > 0  */
while (ptr != NULL)
{
if (count[i] == 0)
++i;
else
{
ptr->data = i;
--count[i];
ptr = ptr->next;
}
}
}

/* Function to push a node */
void push (struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data  */
new_node->data  = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print linked list */
void printList(struct Node *node)
{
while (node != NULL)
{
printf("%d  ", node->data);
node = node->next;
}
printf("n");
}

/* Drier program to test above function*/
int main(void)
{

return 0;
}
```

## Java

```// Java program to sort a linked list of 0, 1 and 2
{

class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}

void sortList()
{
// initialise count of 0 1 and 2 as 0
int count[] = {0, 0, 0};

/* count total number of '0', '1' and '2'
* count[0] will store total number of '0's
* count[1] will store total number of '1's
* count[2] will store total number of '2's  */
while (ptr != null)
{
count[ptr.data]++;
ptr = ptr.next;
}

int i = 0;

/* Let say count[0] = n1, count[1] = n2 and count[2] = n3
* now start traversing list from head node,
* 1) fill the list with 0, till n1 > 0
* 2) fill the list with 1, till n2 > 0
* 3) fill the list with 2, till n3 > 0  */
while (ptr != null)
{
if (count[i] == 0)
i++;
else
{
ptr.data= i;
--count[i];
ptr = ptr.next;
}
}
}

/* Utility functions */

/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

/* Function to print linked list */
void printList()
{
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}

/* Drier program to test above functions */
public static void main(String args[])
{

/* Constructed Linked List is 1->2->3->4->5->6->7->
8->8->9->null */
llist.push(0);
llist.push(1);
llist.push(0);
llist.push(2);
llist.push(1);
llist.push(1);
llist.push(2);
llist.push(1);
llist.push(2);

llist.printList();

llist.sortList();

llist.printList();
}
}
/* This code is contributed by Rajat Mishra */
```

## Python

```
# Python program to sort a linked list of 0, 1 and 2
def __init__(self):

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

def sortList(self):

# initialise count of 0 1 and 2 as 0
count = [0, 0, 0]

# count total number of '0', '1' and '2'
# * count[0] will store total number of '0's
# * count[1] will store total number of '1's
# * count[2] will store total number of '2's
while ptr != None:
count[ptr.data]+=1
ptr = ptr.next

i = 0

# Let say count[0] = n1, count[1] = n2 and count[2] = n3
# * now start traversing list from head node,
# * 1) fill the list with 0, till n1 > 0
# * 2) fill the list with 1, till n2 > 0
# * 3) fill the list with 2, till n3 > 0
while ptr != None:
if count[i] == 0:
i+=1
else:
ptr.data = i
count[i]-=1
ptr = ptr.next

# Utility functions
# Inserts a new Node at front of the list.
def push(self, new_data):

# 1 & 2: Allocate the Node &
# Put in the data
new_node = self.Node(new_data)

# 3. Make next of new Node as head

# 4. Move the head to point to new Node

# Function to print linked list
def printList(self):
while temp != None:
print str(temp.data),
temp = temp.next
print ''

# Drier program to test above functions
llist.push(0)
llist.push(1)
llist.push(0)
llist.push(2)
llist.push(1)
llist.push(1)
llist.push(2)
llist.push(1)
llist.push(2)

llist.printList()

llist.sortList()

llist.printList()

# This code is contributed by BHAVYA JAIN
```

Output:
```Linked List Before Sorting
2  1  2  1  1  2  0  1  0
0  0  1  1  1  1  2  2  2```

Time Complexity: O(n) where n is number of nodes in linked list.
Auxiliary Space: O(1)

Sort a linked list of 0s, 1s and 2s by changing links

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.7 Average Difficulty : 1.7/5.0
Based on 149 vote(s)