Javascript Program For Sorting A Linked List Of 0s, 1s And 2s
Last Updated :
22 Dec, 2021
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:
Javascript
<script>
var head;
class Node
{
constructor(val)
{
this .data = val;
this .next = null ;
}
}
function sortList()
{
var count = [ 0, 0, 0 ];
var ptr = head;
while (ptr != null )
{
count[ptr.data]++;
ptr = ptr.next;
}
var i = 0;
ptr = head;
while (ptr != null )
{
if (count[i] == 0)
i++;
else
{
ptr.data = i;
--count[i];
ptr = ptr.next;
}
}
}
function push(new_data)
{
var new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
function printList()
{
var temp = head;
while (temp != null )
{
document.write(temp.data + " " );
temp = temp.next;
}
document.write( "<br/>" );
}
push(0);
push(1);
push(0);
push(2);
push(1);
push(1);
push(2);
push(1);
push(2);
document.write(
"Linked List before sorting<br/>" );
printList();
sortList();
document.write(
"Linked List after sorting<br/>" );
printList();
</script>
|
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!
Share your thoughts in the comments
Please Login to comment...