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

PROBLEM :

Given a linked list of 0s, 1s and 2s, sort it.

Input:

Complete the method which takes one argument: the head of the linked list. The program should not read any input from stdin/console.
The struct Node has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.

Output: The functon should not print any output to stdin/console.


Example:

Input:
1 2 2 1 2 0 2 2

Output:
0 1 1 2 2 2 2 2

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*
  Sort the list of 0's,1's and 2's
  The input list will have at least one element
  Node is defined as
  struct node
  {
     int data;
     struct node *next;
  }

*/


void sortList(struct node *head)
{
   if(head==NULL)
    return ;
   
    int one,zero,two ;
    one=0 ;
    zero=0 ;
    two=0 ;
   
    struct node *temp ;
    temp=head ;
   
    while(temp!=NULL)
    {
        if(temp->data==0)
            zero++ ;
        else if(temp->data==1)
            one++ ;
        else if(temp->data==2)
            two++ ;
            temp=temp->next ;
    }
   
    temp=head ;
   
        while(zero!=0)
        {
            temp->data=0 ;
            temp=temp->next ;
            zero-- ;
        }
        while(one!=0)
        {
            temp->data=1 ;
            temp=temp->next ;
            one-- ;
        }
        while(two!=0)
        {
            temp->data=2 ;
            temp=temp->next ;
            two-- ;
        }
       
   
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )