Huffman coding

I was trying to implement huffmann coding from here.

First code

Second code

Both codes are almost same and some changes are in lines 56-67. but the first one does’nt work and goes into infinite loop but the second one just works fine can somebody tell me why the first code is not working?

You are making node to point itself in first code, So when you call printCodes it will never end because of self loop.

       node* t=new node('$',0);
		t->p.first= t->l->p.first + t->r->p.first;

this snippet from your code. Say t is pointing to some address X. You are pushing the same address into priority_queue repeatedly. After some iterations X will point itself(X->l = X and X->r = X) but in code 2 you are creating new node at every step (no node will point itself)that’s why it’s working fine.

1 Like

Thanks @srikanth_16

pointers sucks -_-