×

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

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

In this, we are given a linked list of 0s, 1s, and 2s, and we need to 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

Method:

This method sorts the list using the below steps:

  • Firstly, we will traverse the entire list and then count 0s, 1s, and 2s. Assume they are n1, n2, and n3, respectively.
  • Now, we will traverse the linked list again and fill the first n1 nodes with 0, n2 nodes with 1, and n2 nodes with 2.

C Program to sort a linked list of 0s, 1s or 2s

 #include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node * next;
};
struct node * start = NULL;
// For inserting the elements in the linked list
void add(int item)
{
struct node * t, * p;
t = (struct node *)malloc( sizeof( struct node ));
if(start == NULL)
{
start = t;
start -> info = item;
start -> next = NULL;
return;
}
else
{
struct node * p = start;
while(p -> next != NULL)
{
p = p -> next;
}
p -> next = t;
p = p -> next;
p -> info = item;
p -> next = NULL;
}
}
// For sorting the linked list of 0s, 1s and 2s
void sortList(struct node * head)
{
    int count[3] = {0, 0, 0};  // Initialize count of '0', '1' and '2' as 0
    struct node * ptr = head;
    while (ptr != NULL)
    {
        count[ptr -> info] += 1;
        ptr = ptr -> next;
    }
    int i = 0;
    ptr = head;
    while (ptr != NULL)
    {
        if (count[i] == 0)
            ++i;
        else
        {
            ptr->info = i;
            --count[i];
            ptr = ptr -> next;
        }
    }
}
// To display the elements of the linked list
void traverse(struct node * t)
{
if(t == NULL)
{
            printf(" Linked list is empty\n");
                                    }
                                    while(t -> next != NULL)
                                    {
                        printf("%d -> ",t -> info);
                        t = t -> next;
                        }
                        printf("%d\n",t -> info);
}
// Driver Function
int main()
{
    add(1);
    add(0);
    add(2);
    add(0);
    add(1);
    add(1);
    add(2);
    add(2);
   add(0);
   add(1);
    printf("Given Linked List: \n");
    traverse(start);
    sortList (start);
    printf("Linked List After sorting: \n");
    traverse(start);
    return 0;
} 

Output:

Sort the linked list

Time Complexity: The time complexity of this method is O(n), where n is the number of nodes in the linked list.

Auxiliary Space: The time complexity of this method is O(1).


Related Topics

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Polish Notation in Data Structures

Arithmetic Expression: An arithmetic expression is defined as several operands or data items combined using several operators. For example; a+b*(c-d) is an expression. Operands: Operands represent the data in an expression...

2 minutes read.

Given a Binary Tree, find its Minimum Depth

Implementation // Creating a C++ program or implementation to search and explore the minimum depth of a given binary tree.  #include<bits/stdc++.h> using namespace std; // Creating a new binary tree node struct __nod { int record; struct __nod*...

5 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

5 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

3 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Stack Using Array

Stack – A Stack is a linear abstract data type used to store elements. It is also called last in first out or first in last out data structure because...

6 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Given a Binary Tree, Check if it's balanced

Implementation /*Creating a C++ program that will help us identify whether the given tree is height-balanced or not.  */ #include <bits/stdc++.h> using namespace std; /* A particular binary tree node consists of data with some...

4 minutes read.

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

Sum of Nodes in a Binary Tree

In this article, we will see the sample problems that will help us understand the concept and summation of all the nodes in the binary tree. Implementation /* creating a program that...

4 minutes read.