For everyone looking for count sol c++


#1

ListNode* Solution::solve(ListNode* A) {
//there might be different ways but best would be to count and then change
int z=0,o=0;
ListNode* temp=A;
while(temp!=NULL){
if(temp->val==0)z++;
else o++;
temp=temp->next;
}
while(A!=NULL){
if(z>0){
A->val=0;
z–;
}else{
A->val=1;
}
A=A->next;
}
return A;
}


#2

thanks man ,really helpful.


#3

I think that’s a great way. But it requires traversing the whole list twice. A better solution would be traversing the list only once.


#4

just one modification before starting the second while initialize temp=A;
else at the end A will become null nd the function will return A that is null;
so return temp at the end