Sort a Linked List of 0s and 1s
Last Updated :
18 Feb, 2023
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)
Better Approach: The simplest approach to solve the given problem can be to traverse the given linked list and store the values in the linked list in an array and then sort the array by using the sort function on array. Then traverse the linked list again and change the values of nodes by the values of array. In this way even the linked lists with values other than 0s and 1s can be sorted. Since the problem states that the linked list initially contain only 0s and 1s, so we can further optimize this approach.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
};
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
}
void sortList(Node* head)
{
if ((head == NULL) || (head->next == NULL)) {
return ;
}
vector< int > nums;
Node* temp = head;
while (temp != NULL) {
nums.push_back(temp->data);
temp = temp->next;
}
sort(nums.begin(), nums.end());
temp = head;
int i = 0;
while (i < nums.size()) {
temp->data = nums[i];
temp = temp->next;
i++;
}
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
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);
cout << "Linked List (before sorting) : " ;
printList(head);
sortList(head);
cout << "\nLinked List (after sorting) : " ;
printList(head);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Node {
int data;
Node next;
}
class GFG {
static void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
}
static void sortList(Node head)
{
if (head == null || head.next == null ) {
return ;
}
List<Integer> nums = new ArrayList<>();
Node temp = head;
while (temp != null ) {
nums.add(temp.data);
temp = temp.next;
}
Collections.sort(nums);
temp = head;
int i = 0 ;
while (i < nums.size()) {
temp.data = nums.get(i);
temp = temp.next;
i++;
}
}
static Node push(Node head, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head;
return new_node;
}
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 );
System.out.print( "Linked List (before sorting) : " );
printList(head);
sortList(head);
System.out.print(
"\nLinked List (after sorting) : " );
printList(head);
}
}
|
Python3
class Node:
def __init__( self , data = None ):
self .data = data
self . next = None
def printList(node):
while node:
print (node.data, end = ' ' )
node = node. next
def sortList(head):
if not head or not head. next :
return
nums = []
temp = head
while temp:
nums.append(temp.data)
temp = temp. next
nums.sort()
temp = head
i = 0
while i < len (nums):
temp.data = nums[i]
temp = temp. next
i + = 1
def push(head, new_data):
new_node = Node(new_data)
new_node. next = head
return new_node
if __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 )
print ( "Linked List (before sorting) : " , end = ' ' )
printList(head)
sortList(head)
print ( "\nLinked List (after sorting) : " , end = ' ' )
printList(head)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
class Node {
public int data;
public Node next;
}
static void PrintList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
static void SortList( ref Node head)
{
if (head == null ) {
return ;
}
List< int > nums = new List< int >();
Node temp = head;
while (temp != null ) {
nums.Add(temp.data);
temp = temp.next;
}
nums.Sort();
temp = head;
int i = 0;
while (i < nums.Count) {
temp.data = nums[i];
temp = temp.next;
i++;
}
}
static Node Push(Node head, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head;
return new_node;
}
static public void Main()
{
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);
Console.Write( "Linked List (before sorting) : " );
PrintList(head);
SortList( ref head);
Console.Write( "\nLinked List (after sorting) : " );
PrintList(head);
}
}
|
Javascript
<script>
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
function printList(node) {
let curr = node;
let str = "" ;
while (curr !== null ) {
str += curr.data + " " ;
curr = curr.next;
}
document.write(str);
}
function sortList(head) {
if (!head || !head.next) {
return ;
}
let nums = [];
let curr = head;
while (curr !== null ) {
nums.push(curr.data);
curr = curr.next;
}
nums.sort( function (a, b) {
return a - b;
});
curr = head;
let i = 0;
while (i < nums.length) {
curr.data = nums[i];
curr = curr.next;
i++;
}
}
function push(head, newData) {
let newNode = new Node();
newNode.data = newData
newNode.next = head;
return newNode;
}
let 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);
document.write( "Linked List (before sorting) : " );
printList(head);
sortList(head);
document.write( "<br>Linked List (after sorting) : " );
printList(head);
</script>
|
Output
Linked List (before sorting) : 0 1 1 1 1 1 0 1 0
Linked List (after sorting) : 0 0 0 1 1 1 1 1 1
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++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* next;
};
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " " ;
node = node->next;
}
}
void sortList(Node* head)
{
if ((head == NULL) || (head->next == NULL)) {
return ;
}
int count0 = 0, count1 = 0;
Node* temp = head;
while (temp != NULL) {
if (temp->data == 0) {
count0++;
}
else {
count1++;
}
temp = temp->next;
}
temp = head;
while (count0--) {
temp->data = 0;
temp = temp->next;
}
while (count1--) {
temp->data = 1;
temp = temp->next;
}
}
void push(Node** head_ref, int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
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);
cout << "Linked List (before sorting) : " ;
printList(head);
sortList(head);
cout << "\nLinked List (after sorting) : " ;
printList(head);
return 0;
}
|
Java
import java.util.*;
class GFG{
static class Node {
int data;
Node next;
};
static void printList(Node node)
{
while (node != null ) {
System.out.print(node.data+ " " );
node = node.next;
}
}
static void sortList(Node head)
{
if ((head == null )
|| (head.next == null )) {
return ;
}
int count0 = 0 , count1 = 0 ;
Node temp = head;
while (temp != null ) {
if (temp.data == 0 ) {
count0++;
}
else {
count1++;
}
temp = temp.next;
}
temp = head;
while (count0> 0 ) {
temp.data = 0 ;
temp = temp.next;
count0--;
}
while (count1> 0 ) {
temp.data = 1 ;
temp = temp.next;
count1--;
}
printList(head);
}
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
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);
}
}
|
Python3
class Node:
def __init__( self ):
self .data = 0 ;
self . next = None ;
def printList(Node):
while (Node ! = None ):
print (Node.data, end = " " );
Node = Node. next ;
def sortList(head):
if ((head = = None ) or (head. next = = None )):
return ;
count0 = 0 ; count1 = 0 ;
temp = head;
while (temp ! = None ):
if (temp.data = = 0 ):
count0 + = 1 ;
else :
count1 + = 1 ;
temp = temp. next ;
temp = head;
while (count0 > 0 ):
temp.data = 0 ;
temp = temp. next ;
count0 - = 1 ;
while (count1 > 0 ):
temp.data = 1 ;
temp = temp. next ;
count1 - = 1 ;
printList(head);
def push(head_ref, new_data):
new_Node = Node();
new_Node.data = new_data;
new_Node. next = head_ref;
head_ref = new_Node;
return head_ref;
if __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);
|
C#
using System;
public class GFG {
public class Node {
public int data;
public Node next;
};
static void printList(Node node) {
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
static void sortList(Node head) {
if ((head == null ) || (head.next == null )) {
return ;
}
int count0 = 0, count1 = 0;
Node temp = head;
while (temp != null ) {
if (temp.data == 0) {
count0++;
}
else {
count1++;
}
temp = temp.next;
}
temp = head;
while (count0 > 0) {
temp.data = 0;
temp = temp.next;
count0--;
}
while (count1 > 0) {
temp.data = 1;
temp = temp.next;
count1--;
}
printList(head);
}
static Node push(Node head_ref, int new_data) {
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
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);
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
function printList(node) {
while (node != null ) {
document.write(node.data + " " );
node = node.next;
}
}
function sortList(head)
{
if ((head == null ) || (head.next == null )) {
return ;
}
var count0 = 0, count1 = 0;
var temp = head;
while (temp != null ) {
if (temp.data == 0) {
count0++;
}
else {
count1++;
}
temp = temp.next;
}
temp = head;
while (count0 > 0) {
temp.data = 0;
temp = temp.next;
count0--;
}
while (count1 > 0) {
temp.data = 1;
temp = temp.next;
count1--;
}
printList(head);
}
function push(head_ref , new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
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);
</script>
|
Output:
0 0 0 1 1 1 1 1 1
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...