Open In App

Sort a Linked List of 0s and 1s

Last Updated : 09 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given the singly 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 -> NULL 
Output: 0 -> 0 -> 1 -> 1 -> 1 -> NULL

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

[Naive Approach] Convert Linked List to Array – O(nlogn) Time and O(n) Space:

The idea is to traverse the given linked list from head and store the node values in an array and then sort the array by using the custom sort function on array. After sorting, the algorithm traverses the linked list again from head node and updating each node’s value with the sorted values from the array. This method effectively sorts the list without rearranging the nodes themselves, ensuring that the original node structure remains unchanged.

Below is the implementation of the above approach:

C++
// Iterative C++ program to sort a linked list 
// of binary integers 0s and 1s

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to sort the linked list
Node* sortList(Node* head) {

    // Vector to store the values from linked list
    vector<int> nums;

    Node* curr = head;

    // Traverse the linked list and store 
    // the values in vector
    while (curr != nullptr) {
        nums.push_back(curr->data);
        curr = curr->next;
    }

    // Sort the vector containing binary integers
    sort(nums.begin(), nums.end());

    // Traverse the linked list again and 
    // assign sorted values
    curr = head;
    for (int i = 0; i < nums.size(); i++) {
        curr->data = nums[i];
        curr = curr->next;
    }

    // Return the head of the sorted linked list
    return head;
}

void printList(Node* head) {
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
}

int main() {

    // Create a hard-coded linked list:
    // 1 -> 0 -> 1 -> 0 -> 1
    Node* head = new Node(1);
    head->next = new Node(0);
    head->next->next = new Node(1);
    head->next->next->next = new Node(0);
    head->next->next->next->next = new Node(1);

    head = sortList(head);

    printList(head);

    return 0;
}
Java
// Iterative Java program to sort a linked 
// list of binary integers 0s and 1s

import java.util.*;

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    // Function to sort the linked list 0 1
    static Node sortList(Node head) {
        
        // List to store the values from linked list
        ArrayList<Integer> nums = new ArrayList<>();
        
        Node curr = head;
        
        // Traverse the linked list and store 
        //the values in list
        while (curr != null) {
            nums.add(curr.data);
            curr = curr.next;
        }
        
        // Sort the list containing binary integers
        Collections.sort(nums);
        
        // Traverse the linked list again and 
        // assign sorted values
        curr = head;
        for (int i = 0; i < nums.size(); i++) {
            curr.data = nums.get(i);
            curr = curr.next;
        }

        return head;
    }

    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
    }

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 1 -> 0 -> 1 -> 0 -> 1
        Node head = new Node(1);
        head.next = new Node(0);
        head.next.next = new Node(1);
        head.next.next.next = new Node(0);
        head.next.next.next.next = new Node(1);

        head = sortList(head);

        printList(head);
    }
}
Python
# Iterative Python program to sort a linked list
# of binary integers 0s and 1s

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def sortList(head):
    
    # List to store the values from linked list
    nums = []
    
    curr = head
    
    # Traverse the linked list and store the 
    # values in list
    while curr is not None:
        nums.append(curr.data)
        curr = curr.next
    
    # Sort the list containing binary integers
    nums.sort()
    
    # Traverse the linked list again and 
    # assign sorted values
    curr = head
    for i in range(len(nums)):
        curr.data = nums[i]
        curr = curr.next
    
    # Return the head of the sorted linked list
    return head

def printList(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next

if __name__ == "__main__":
    
    # Create a hard-coded linked list:
    # 1 -> 0 -> 1 -> 0 -> 1
    head = Node(1)
    head.next = Node(0)
    head.next.next = Node(1)
    head.next.next.next = Node(0)
    head.next.next.next.next = Node(1)
    
    head = sortList(head)
    
    printList(head)
C#
// Iterative C# program to sort a linked list
// of binary integers 0s and 1s
using System;
using System.Collections.Generic;

class Node {
  
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {
  
    // Function to sort the linked list of binary integers
    static Node SortList(Node head) {
      
        // List to store the values from linked list
        List<int> nums = new List<int>();

        Node curr = head;

        // Traverse the linked list and store values in list
        while (curr != null) {
            nums.Add(curr.data);
            curr = curr.next;
        }

        // Sort the list containing binary integers
        nums.Sort();

        // Traverse the linked list again and 
      	// assign sorted values
        curr = head;
        for (int i = 0; i < nums.Count; i++) {
            curr.data = nums[i];
            curr = curr.next;
        }

        return head;
    }

    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
    }

    static void Main() {
      
        // Create a hard-coded linked list:
        // 1 -> 0 -> 1 -> 0 -> 1
        Node head = new Node(1);
        head.next = new Node(0);
        head.next.next = new Node(1);
        head.next.next.next = new Node(0);
        head.next.next.next.next = new Node(1);

        head = SortList(head);

        PrintList(head);
    }
}
JavaScript
// Iterative JavaScript program to sort a linked list
// of binary integers 0s and 1s

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Function to sort the linked list
// of binary integers
function sortList(head) {
    
    // Array to store the values from linked list
    const nums = [];
    
    let curr = head;

    // Traverse the linked list and store 
    // values in array
    while (curr != null) {
        nums.push(curr.data);
        curr = curr.next;
    }

    // Sort the array containing binary integers
    nums.sort((a, b) => a - b);

    // Traverse the linked list again and
    // assign sorted values
    curr = head;
    for (let i = 0; i < nums.length; i++) {
        curr.data = nums[i];
        curr = curr.next;
    }
    
    return head;
}

function printList(head) {
    let curr = head;
    while (curr != null) {
        process.stdout.write(curr.data + " ");
        curr = curr.next;
    }
}

// Create a hard-coded linked list:
// 1 -> 0 -> 1 -> 0 -> 1
const head = new Node(1);
head.next = new Node(0);
head.next.next = new Node(1);
head.next.next.next = new Node(0);
head.next.next.next.next = new Node(1);

const sortedHead = sortList(head);

printList(sortedHead);

Output
0 0 1 1 1 

Time Complexity: O(n log n), for sorting the array, where n is the number of nodes.
Auxiliary Space: O(n), for storing node values in an array.

[Expected Approach] By Counting 0’s and 1’s- O(n) Time and O(1) Space:

In this method we first traverse the list to count the number of 0s and 1s. After obtaining the counts, we iterates through the list again, updating each node’s value based on the counts (assigning 0s until their count is exhausted, then assigning 1s). This method efficiently sorts the list by counting and overwriting values without needing additional space.

Below is the implementation of the above approach:

C++
// C++ program to sort a 0 1 linked list
// using counting sort
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to sort the linked 
// list of binary integers
Node* sortList(Node* head) {

    // Count the number of 0s and 1s
    int count0 = 0, count1 = 0;
    Node* curr = head;

    while (curr != nullptr) {
      
        if (curr->data == 0) {
            count0++;
        } 
        else {
            count1++;
        }
        curr = curr->next;
    }

    // Update the values of nodes based on counts
    curr = head;
    while (curr != nullptr) {
      
        if (count0 > 0) {
            curr->data = 0;
            count0--;
        } 
        else {
            curr->data = 1;
        }
        curr = curr->next;
    }

    return head;
}

void printList(Node* head) {
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
}

int main() {

    // Create a hard-coded linked list of binary integers:
    // 1 -> 0 -> 1 -> 0 -> 1
    Node* head = new Node(1);
    head->next = new Node(0);
    head->next->next = new Node(1);
    head->next->next->next = new Node(0);
    head->next->next->next->next = new Node(1);

    head = sortList(head);

    printList(head);

    return 0;
}
C
// C Program to sort a 0 1 Linked List
// using counting sort
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to sort the linked list 
struct Node* sortList(struct Node* head) {
  
    // Count the number of 0s and 1s
    int count0 = 0, count1 = 0;
    struct Node* curr = head;

    while (curr != NULL) {
        if (curr->data == 0) {
            count0++;
        } 
        else {
            count1++;
        }
        curr = curr->next;
    }

    // Update the values of nodes based on counts
    curr = head;
    while (curr != NULL) {
        if (count0 > 0) {
            curr->data = 0;
            count0--;
        } 
        else {
            curr->data = 1;
        }
        curr = curr->next;
    }
    return head;
}

void printList(struct Node* head) {
    struct Node* curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
}


struct Node* createNode(int data) {
    struct Node* newNode 
      = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

int main() {
  
    // Create a hard-coded linked list:
    // 1 -> 0 -> 1 -> 0 -> 1
    struct Node* head = createNode(1);
    head->next = createNode(0);
    head->next->next = createNode(1);
    head->next->next->next = createNode(0);
    head->next->next->next->next = createNode(1);

    head = sortList(head);

    printList(head);

    return 0;
}
Java
// Java program to sort a 0 1 linked list
// using counting sort
class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

public class GfG {

    // Function to sort the linked list of binary integers
    static Node sortList(Node head) {
        
        // Count the number of 0s and 1s
        int count0 = 0, count1 = 0;
        Node curr = head;

        while (curr != null) {
          
            if (curr.data == 0) {
                count0++;
            } 
            else {
                count1++;
            }
            curr = curr.next;
        }

        // Update the values of nodes based on counts
        curr = head;
        while (curr != null) {
          
            if (count0 > 0) {
                curr.data = 0;
                count0--;
            } 
            else {
                curr.data = 1;
            }
            curr = curr.next;
        }

        return head;
    }

    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
    }

    public static void main(String[] args) {

        // Create a hard-coded linked list:
        // 1 -> 0 -> 1 -> 0 -> 1
        Node head = new Node(1);
        head.next = new Node(0);
        head.next.next = new Node(1);
        head.next.next.next = new Node(0);
        head.next.next.next.next = new Node(1);

        head = sortList(head);

        printList(head);
    }
}
Python
# Python program to sort a 0 1 linked list
# using Counting Sort
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def sortList(head):
  
    # Count the number of 0s and 1s
    count0 = 0
    count1 = 0
    curr = head

    while curr is not None:
        if curr.data == 0:
            count0 += 1
        else:
            count1 += 1
        curr = curr.next

    # Update the values of nodes based on counts
    curr = head
    while curr is not None:
        if count0 > 0:
            curr.data = 0
            count0 -= 1
        else:
            curr.data = 1
        curr = curr.next

    return head

def printList(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next

# Main function to test the above code
if __name__ == "__main__":
  
    # Create a hard-coded linked list of binary integers:
    # 1 -> 0 -> 1 -> 0 -> 1
    head = Node(1)
    head.next = Node(0)
    head.next.next = Node(1)
    head.next.next.next = Node(0)
    head.next.next.next.next = Node(1)

    head = sortList(head)

    printList(head)
C#
// C# program to sort a 0 1 linked list 
// using counting sort
using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {
    // Function to sort the linked list of binary integers
    static Node SortList(Node head) {
      
        // Count the number of 0s and 1s
        int count0 = 0, count1 = 0;
        Node curr = head;

        while (curr != null) {
          
            if (curr.data == 0) {
                count0++;
            }
            else {
                count1++;
            }
            curr = curr.next;
        }

        // Update the values of nodes
      	// based on counts
        curr = head;
        while (curr != null) {
          
            if (count0 > 0) {
                curr.data = 0;
                count0--;
            }
            else {
                curr.data = 1;
            }
            curr = curr.next;
        }

        return head;
    }

    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
    }

    static void Main() {
      
        // Create a hard-coded linked list:
        // 1 -> 0 -> 1 -> 0 -> 1
        Node head = new Node(1);
        head.next = new Node(0);
        head.next.next = new Node(1);
        head.next.next.next = new Node(0);
        head.next.next.next.next = new Node(1);

        head = SortList(head);

        PrintList(head);
    }
}
JavaScript
// JavaScript program to sort a 0 1
// linked list using counting sort

class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}

// Function to sort the linked list 
// of binary integers
function sortList(head) {

    // Count the number of 0s and 1s
    let count0 = 0;
    let count1 = 0;
    let curr = head;

    while (curr !== null) {
    
        if (curr.data === 0) {
            count0++;
        } 
        else {
            count1++;
        }
        curr = curr.next;
    }

    // Update the values of nodes based on counts
    curr = head;
    while (curr !== null) {
    
        if (count0 > 0) {
            curr.data = 0;
            count0--;
        } 
        else {
            curr.data = 1;
        }
        curr = curr.next;
    }
    return head;
}

function printList(head) {
    let curr = head;
    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        curr = curr.next;
    }
}

// Create a hard-coded linked list of binary integers:
// 1 -> 0 -> 1 -> 0 -> 1
const head = new Node(1);
head.next = new Node(0);
head.next.next = new Node(1);
head.next.next.next = new Node(0);
head.next.next.next.next = new Node(1);

const sortedHead = sortList(head);

printList(sortedHead);

Output
0 0 1 1 1 

Time Complexity: O(n), where n is the number of nodes, since we make two passes through the list.
Space Complexity: O(1)



Next Article

Similar Reads