Sort a Linked List of 0s, 1s and 2s

Write code to sort a linked list of 0s, 1s and 2s. Given a linked list which only consists of 0s, 1s and 2s. Write a function to sort a linked list.

For example:

Input:  2 -> 0 -> 1 -> 0 -> 2 -> 0 -> 1 -> NULL

Output: 0 -> 0 -> 0 -> 1 -> 1 -> 2 -> 2 -> NULL

sort a linked list of 0s, 1s and 2s

This problem is similar to sort an array of 0s, 1s and 2s. Let’s discuss how we can solve this problem in minimum time complexity.

Programming video tutorials

Sort a Linked List of 0s, 1s and 2s | Java Code

There are multiple approaches we can use to solve this problem. In this tutorial, I am going to discuss an approach to count the number of 0s, 1s and 2s and then we put the nodes in a correct position.

To sort a given linked list, we need to follow these steps:

i) Count the number of 0s, 1s, and 2s present in a linked list. Let the count be n1, n2, and n3.

ii) Traverse the linked list again and fill the first n1 nodes with zero, then next n2 nodes with one and finally n3 nodes with two.

The time complexity of this approach is O(n) and its space complexity is O(1).

Programming questions on Linked List

Complete Java code for sorting a linked list of 0s, 1s and 2s.

Tagged . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.