Saved Bookmarks
| 1. |
Write a function to sort a linked list of 0s, 1s and 2s |
Answer»
struct Node { int data; Node *left; Node *right; } //function take the head of the linked list as a parameter void sortList(Node *head) { //if linked list is empty then return back if(head==NULL) return; else { Node *temp=head; Node *temp1=head; //to store count of 0s, 1s, and 2s int count0=0,count1=0,count2=0; //calculating the count of 0s, 1s, and 2s while(temp!=NULL) { if(temp->data==0) count0++; else if(temp->data==1) count1++; else count2++; temp=temp->next; } //iterating over count of 0s and filling the linked list while(count0!=0) { temp1->data=0; temp1=temp1->next; count0--; } //iterating over count of 1s and filling the linked list while(count1!=0) { temp1->data=1; temp1=temp1->next; count1--; } //iterating over count of 2s and filling the linked list while(count2!=0) { temp1->data=2; temp1=temp1->next; count2--; } } }
|
|