Sort a Linked List of 0s and 1s

03 Feb, 2022
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:
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++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Link list nodeclass Node {public:    int data;    Node* next;}; // Function to print linked listvoid 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 1svoid 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 nodevoid 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 Codeint 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 program for the above approachimport 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
# Python program for the above approach # Link list Nodeclass Node:    def __init__(self):        self.data = 0;        self.next = None; # Function to print linked listdef printList(Node):     # Iterate until Node is NOT None    while (Node != None):         # Print data        print(Node.data, end=" ");        Node = Node.next;     # Function to sort the linked list# consisting of 0s and 1sdef sortList(head):    # Base Case    if ((head == None) or (head.next == None)):        return;         # Store the count of 0s and 1s    count0 = 0; count1 = 0;     # Stores the head Node    temp = head;     # Traverse the list Head    while (temp != None):         # If Node.data value is 0        if (temp.data == 0):             # Increment count0 by 1            count0 += 1;                 # Otherwise, increment the        # count of 1s        else:            count1 += 1;                 # 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 -= 1;         # Now, update the value of the    # remaining count1 Nodes as 1    while (count1 > 0):        temp.data = 1;        temp = temp.next;        count1 -= 1;         # Print the Linked List    printList(head); # Function to push a Nodedef push(head_ref, new_data):       # Allocate Node    new_Node = 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 Codeif __name__ == '__main__':    head = None;    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# program for the above approachusing System; public class GFG {     // Link list nodepublic    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
<script>// javascript program for the above approach     // Link list nodeclass Node {    constructor() {        this.data = 0;        this.next = null;    }}     // Function to print linked list    function printList(node) {         // Iterate until node is NOT null        while (node != null) {             // Print the data            document.write(node.data + " ");            node = node.next;        }    }     // Function to sort the linked list    // consisting of 0s and 1s    function sortList(head)    {             // Base Case        if ((head == null) || (head.next == null)) {            return;        }         // Store the count of 0s and 1s        var count0 = 0, count1 = 0;         // Stores the head node        var 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    function push(head_ref , new_data)    {             // Allocate node        var 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           var 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</script>
0 0 0 1 1 1 1 1 1
 
Time Complexity: O(N)Auxiliary Space: O(1)
umadevi9616
khushboogoyal499
simranarora5sos
adnanirshad158
surinderdawra388
Linked Lists
Linked-List-Sorting
Linked List
Sorting
Linked List
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Rearrange a given linked list in-place.
Types of Linked List
Find first node of loop in a linked list
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm