Given a linked list of 0s, 1s and 2s, sort it.
Examples:
Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL
Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL
Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL
Source: Microsoft Interview | Set 1
Following steps can be used to sort the given linked list.
- Traverse the list and count the number of 0s, 1s, and 2s. Let the counts be n1, n2, and n3 respectively.
- Traverse the list again, fill the first n1 nodes with 0, then n2 nodes with 1, and finally n3 nodes with 2.
Below image is a dry run of the above approach:

Below is the implementation of the above approach:
Python
class LinkedList( object ):
def __init__( self ):
self .head = None
class Node( object ):
def __init__( self , d):
self .data = d
self . next = None
def sortList( self ):
count = [ 0 , 0 , 0 ]
ptr = self .head
while ptr ! = None :
count[ptr.data] + = 1
ptr = ptr. next
i = 0
ptr = self .head
while ptr ! = None :
if count[i] = = 0 :
i + = 1
else :
ptr.data = i
count[i] - = 1
ptr = ptr. next
def push( self , new_data):
new_node = self .Node(new_data)
new_node. next = self .head
self .head = new_node
def printList( self ):
temp = self .head
while temp ! = None :
print str (temp.data),
temp = temp. next
print ''
llist = LinkedList()
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 )
print "Linked List before sorting"
llist.printList()
llist.sortList()
print "Linked List after sorting"
llist.printList()
|
Output:
Linked List Before Sorting
2 1 2 1 1 2 0 1 0
Linked List After Sorting
0 0 1 1 1 1 2 2 2
Time Complexity: O(n) where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Please refer complete article on Sort a linked list of 0s, 1s and 2s for more details!