• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
August 16, 2024 |900 Views

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

Description
Discussion

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 
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.

Sort a linked list of 0s, 1s and 2s : https://www.geeksforgeeks.org/sort-a-linked-list-of-0s-1s-or-2s/