Sort a linked list of 0s, 1s and 2s[Microsoft,Amazon]

Problem:

Complete the method which takes oneargument: the head ofthe linked list. The programshould not read any input fromstdin/console.
The struct Node has a data part which stores the data and a nextpointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will becalled individually.

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

Problem Link

/*
  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)
{
   //Add code here
   int zero=0,one=0,two=0;
   node *zh,*oh,*th;
   node *p;
   node *tmp=head;
   int f=0,ff=0,fff=0;
   while(tmp!=NULL)
   {
      if(tmp->data==0)
      zero+=1;
      else if(tmp->data==1)
      one+=1;
      else if(tmp->data==2)
      two+=1;
      tmp=tmp->next;
   }
   tmp=head;
   while(tmp!=NULL)
   {
       for(int i=1;i<=zero;i++)
       {
           tmp->data=0;
           tmp=tmp->next;
       }
       for(int i=1;i<=one;i++)
       {
           tmp->data=1;
           tmp=tmp->next;
       }
       for(int i=1;i<=two;i++)
       {
           tmp->data=2;
           tmp=tmp->next;
       }
   }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *