×

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

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end...

3 minutes read.

Implementation of Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.

Selection Sort

In each iteration of the selection sort algorithm, the smallest item from an unsorted list is chosen and placed at the top of the unsorted list. Algorithm of Selection Sorting In order...

3 minutes read.

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.

Function to Delete a Leaf Node from a Binary Tree

Implementation // We are writing a C++ code to eliminate all the leaves from the given value.  #include <bits/stdc++.h> using namespace std; // creating a new binary tree node struct __nod { int record; struct __nod *Lft,...

4 minutes read.

Stack vs Queue: Data Structure

 Difference Between Stack and Queue What is Stack? The LIFO principle applies on insertion and deletion operations of the stack which means last inserted element to the stack will remove first....

3 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Finding the Sum of All Paths in a Binary Tree

Implementation // Writing the C++ program to implement the below approach.  #include <bits/stdc++.h> using namespace std; // creating the new tree node structure. struct Tree__nod { int val; Tree__nod *Lft, *Rt; }; // creating a new function that will...

8 minutes read.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

8 minutes read.

Properties of Binary Tree

Trees are maybe of the most significant datum structures. They are used to store and figure out data. A binarytree is a tree data structure made from nodes, all of which has...

3 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Dijkstra’s vs Bellman-Ford Algorithm

The Dijkstra Algorithm One of the SSSP (Single Source Shortest Path) algorithms is Dijkstra's. As a result, it finds the shortest path between a source node and all other nodes in...

7 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 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.

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.

Insertion Sort vs Selection Sort

In this article, we will discuss insertion sort, Selection sort and the basic differences between these two sorting techniques in detail: What is Insertion Sort? Insertion Sort – The insertion sort is...

5 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.