# Sort a Linked List of 0s and 1s

• Difficulty Level : Basic
• Last Updated : 01 Dec, 2021

Given the head of a Linked List of size N, consisting of binary integers 0s and 1s, the task is to sort the given linked list.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: head = 1 -> 0 -> 1 -> 0 -> 1 -> 0 -> NULL
Output: 0 -> 0 -> 0 -> 1 -> 1 -> 1 -> NULL

Input: head = 1 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 1 -> NULL

Naive Approach: The simplest approach to solve the given problem is to perform the merge sort or insertion sort on the given linked list and sort it. The Implementation of Sorting the Linked list using Merge sort and Sorting the linked list using Insertion sort is discussed already.
Time complexity: O(N * log N)
Auxiliary Space: O(N)

Efficient Approach: The above approach can also be optimized by counting the number of 1s and 0s in the given linked list and update the value of nodes accordingly in the linked list. Follow the steps to solve the problem:

• Traverse the given linked list and store the count of 0s and 1s in variables, say zeroes and ones respectively.
• Now, traverse the linked list again and change the first zeroes nodes with value 0 and then the remaining nodes with the value 1.
• After completing the above steps, print the linked list as the resultant sorted list.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Link list node` `class` `Node {` `public``:` `    ``int` `data;` `    ``Node* next;` `};`   `// Function to print linked list` `void` `printList(Node* node)` `{` `    ``// Iterate until node is NOT NULL` `    ``while` `(node != NULL) {`   `        ``// Print the data` `        ``cout << node->data << ``" "``;` `        ``node = node->next;` `    ``}` `}`   `// Function to sort the linked list` `// consisting of 0s and 1s` `void` `sortList(Node* head)` `{` `    ``// Base Case` `    ``if` `((head == NULL)` `        ``|| (head->next == NULL)) {` `        ``return``;` `    ``}`   `    ``// Store the count of 0s and 1s` `    ``int` `count0 = 0, count1 = 0;`   `    ``// Stores the head node` `    ``Node* temp = head;`   `    ``// Traverse the list Head` `    ``while` `(temp != NULL) {`   `        ``// If node->data value is 0` `        ``if` `(temp->data == 0) {`   `            ``// Increment count0 by 1` `            ``count0++;` `        ``}`   `        ``// Otherwise, increment the` `        ``// count of 1s` `        ``else` `{` `            ``count1++;` `        ``}`   `        ``// Update the temp node` `        ``temp = temp->next;` `    ``}`   `    ``// Update the temp to head` `    ``temp = head;`   `    ``// Traverse the list and update` `    ``// the first count0 nodes as 0` `    ``while` `(count0--) {` `        ``temp->data = 0;` `        ``temp = temp->next;` `    ``}`   `    ``// Now, update the value of the` `    ``// remaining count1 nodes as 1` `    ``while` `(count1--) {` `        ``temp->data = 1;` `        ``temp = temp->next;` `    ``}`   `    ``// Print the Linked List` `    ``printList(head);` `}`   `// Function to push a node` `void` `push(Node** head_ref, ``int` `new_data)` `{` `    ``// Allocate node` `    ``Node* new_node = ``new` `Node();`   `    ``// Put in the data` `    ``new_node->data = new_data;`   `    ``// Link the old list of the` `    ``// new node` `    ``new_node->next = (*head_ref);`   `    ``// Move the head to point to` `    ``// the new node` `    ``(*head_ref) = new_node;` `}`   `// Driver Code` `int` `main(``void``)` `{` `    ``Node* head = NULL;` `    ``push(&head, 0);` `    ``push(&head, 1);` `    ``push(&head, 0);` `    ``push(&head, 1);` `    ``push(&head, 1);` `    ``push(&head, 1);` `    ``push(&head, 1);` `    ``push(&head, 1);` `    ``push(&head, 0);` `    ``sortList(head);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.*;` `class` `GFG{`   `  ``// Link list node` `  ``static` `class` `Node {`   `    ``int` `data;` `    ``Node next;` `  ``};`   `  ``// Function to print linked list` `  ``static` `void` `printList(Node node)` `  ``{`   `    ``// Iterate until node is NOT null` `    ``while` `(node != ``null``) {`   `      ``// Print the data` `      ``System.out.print(node.data+ ``" "``);` `      ``node = node.next;` `    ``}` `  ``}`   `  ``// Function to sort the linked list` `  ``// consisting of 0s and 1s` `  ``static` `void` `sortList(Node head)` `  ``{` `    ``// Base Case` `    ``if` `((head == ``null``)` `        ``|| (head.next == ``null``)) {` `      ``return``;` `    ``}`   `    ``// Store the count of 0s and 1s` `    ``int` `count0 = ``0``, count1 = ``0``;`   `    ``// Stores the head node` `    ``Node temp = head;`   `    ``// Traverse the list Head` `    ``while` `(temp != ``null``) {`   `      ``// If node.data value is 0` `      ``if` `(temp.data == ``0``) {`   `        ``// Increment count0 by 1` `        ``count0++;` `      ``}`   `      ``// Otherwise, increment the` `      ``// count of 1s` `      ``else` `{` `        ``count1++;` `      ``}`   `      ``// Update the temp node` `      ``temp = temp.next;` `    ``}`   `    ``// Update the temp to head` `    ``temp = head;`   `    ``// Traverse the list and update` `    ``// the first count0 nodes as 0` `    ``while` `(count0>``0``) {` `      ``temp.data = ``0``;` `      ``temp = temp.next;` `      ``count0--;` `    ``}`   `    ``// Now, update the value of the` `    ``// remaining count1 nodes as 1` `    ``while` `(count1>``0``) {` `      ``temp.data = ``1``;` `      ``temp = temp.next;` `      ``count1--;` `    ``}`   `    ``// Print the Linked List` `    ``printList(head);` `  ``}`   `  ``// Function to push a node` `  ``static` `Node push(Node head_ref, ``int` `new_data)` `  ``{` `    ``// Allocate node` `    ``Node new_node = ``new` `Node();`   `    ``// Put in the data` `    ``new_node.data = new_data;`   `    ``// Link the old list of the` `    ``// new node` `    ``new_node.next = head_ref;`   `    ``// Move the head to point to` `    ``// the new node` `    ``head_ref = new_node;` `    ``return` `head_ref;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `main(String[] args)` `  ``{` `    ``Node head = ``null``;` `    ``head = push(head, ``0``);` `    ``head = push(head, ``1``);` `    ``head = push(head, ``0``);` `    ``head = push(head, ``1``);` `    ``head = push(head, ``1``);` `    ``head = push(head, ``1``);` `    ``head = push(head, ``1``);` `    ``head = push(head, ``1``);` `    ``head = push(head, ``0``);` `    ``sortList(head);`   `  ``}` `}`   `// This code is contributed by umadevi9616`

## C#

 `// C# program for the above approach` `using` `System;`   `public` `class` `GFG {`   `    ``// Link list node` `public`    `class` `Node {`   `    ``public`    `int` `data;` `    ``public`    `Node next;` `    ``};`   `    ``// Function to print linked list` `    ``static` `void` `printList(Node node) {`   `        ``// Iterate until node is NOT null` `        ``while` `(node != ``null``) {`   `            ``// Print the data` `            ``Console.Write(node.data + ``" "``);` `            ``node = node.next;` `        ``}` `    ``}`   `    ``// Function to sort the linked list` `    ``// consisting of 0s and 1s` `    ``static` `void` `sortList(Node head) {` `        ``// Base Case` `        ``if` `((head == ``null``) || (head.next == ``null``)) {` `            ``return``;` `        ``}`   `        ``// Store the count of 0s and 1s` `        ``int` `count0 = 0, count1 = 0;`   `        ``// Stores the head node` `        ``Node temp = head;`   `        ``// Traverse the list Head` `        ``while` `(temp != ``null``) {`   `            ``// If node.data value is 0` `            ``if` `(temp.data == 0) {`   `                ``// Increment count0 by 1` `                ``count0++;` `            ``}`   `            ``// Otherwise, increment the` `            ``// count of 1s` `            ``else` `{` `                ``count1++;` `            ``}`   `            ``// Update the temp node` `            ``temp = temp.next;` `        ``}`   `        ``// Update the temp to head` `        ``temp = head;`   `        ``// Traverse the list and update` `        ``// the first count0 nodes as 0` `        ``while` `(count0 > 0) {` `            ``temp.data = 0;` `            ``temp = temp.next;` `            ``count0--;` `        ``}`   `        ``// Now, update the value of the` `        ``// remaining count1 nodes as 1` `        ``while` `(count1 > 0) {` `            ``temp.data = 1;` `            ``temp = temp.next;` `            ``count1--;` `        ``}`   `        ``// Print the Linked List` `        ``printList(head);` `    ``}`   `    ``// Function to push a node` `    ``static` `Node push(Node head_ref, ``int` `new_data) {` `        ``// Allocate node` `        ``Node new_node = ``new` `Node();`   `        ``// Put in the data` `        ``new_node.data = new_data;`   `        ``// Link the old list of the` `        ``// new node` `        ``new_node.next = head_ref;`   `        ``// Move the head to point to` `        ``// the new node` `        ``head_ref = new_node;` `        ``return` `head_ref;` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main(String[] args) {` `        ``Node head = ``null``;` `        ``head = push(head, 0);` `        ``head = push(head, 1);` `        ``head = push(head, 0);` `        ``head = push(head, 1);` `        ``head = push(head, 1);` `        ``head = push(head, 1);` `        ``head = push(head, 1);` `        ``head = push(head, 1);` `        ``head = push(head, 0);` `        ``sortList(head);`   `    ``}` `}`   `// This code is contributed by umadevi9616`

## Javascript

 ``

Output:

`0 0 0 1 1 1 1 1 1`

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Recommended Articles
Page :