Sort a linked list of 0s, 1s and 2s by changing links
- Difficulty Level : Medium
- Last Updated : 26 Jul, 2022
Given a linked list of 0s, 1s and 2s, sort it.
Input : 2->1->2->1->1->2->0->1->0 Output : 0->0->1->1->1->1->2->2->2 The sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2. Input : 2->1->0 Output : 0->1->2 The sorted Array is 0, 1, 2
Method 1: Here is a solution discussed in below post that works by changing data of nodes.
Sort a linked list of 0s, 1s and 2s
The above solution does not work when these values have associated data with them. For example, these three represent three colours and different types of objects associated with the colours and sort the objects (connected with a linked list) based on colours.
Method 2: In this post, a new solution is discussed that works by changing links.
Approach: Iterate through the linked list. Maintain 3 pointers named zero, one and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list. Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as dummy headers of three lists.
Linked List Before Sorting 1 2 0 1 Linked List After Sorting 0 1 1 2
- Time Complexity: O(n) where n is a number of nodes in linked list.
Only one traversal of the linked list is needed.
- Auxiliary Space: O(1).
As no extra space is required.
Thanks to Musarrat_123 for suggesting above solution in a comment here.
This article is contributed by Bhaskar Kumar Mishra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.