title: huffman algorithm
body: <p>I'm making a program on the <strong>HUFFMAN ALGORITHM</strong> where I have one class of nodes (<em>hnode</em>) to contain the symbol (<em>name</em>) and its frequency of occurence (<em>freq</em>); and other class (<em>pq</em>) which is used to form the <strong>tree</strong> to get the code for the symbols. I have written only the relevant parts of the classes. Now when I try to run this program it always gets stuck in the while loop (<em>in main()</em>) when it enters <em>the while loop</em> second time. I've tried everything but still couldn't figure out why... Can somebody please help to make this code run !!</p>
  
  <pre><code>#define NPTR hnode*
  class pq;
  class hnode
  {
      string name;
      int freq;
      friend class pq;
  
      public:
  
      NPTR phnode;
      void show () 
      { cout &lt;&lt; "name = " &lt;&lt; name &lt;&lt; endl &lt;&lt; ", freq= " &lt;&lt; freq &lt;&lt;endl ; }
  
      hnode (string x, int fr): name(x), freq(fr)
      {
          phnode = this;
      }
  
      friend hnode operator + (hnode p, hnode q)
      {
          string s = q.name + p.name;
          int f = q.freq + p.freq ;
          hnode foo (s,f);
          return foo;
      }
  };
  
  class pq /// ascending priority queue
  {
      struct node
      {
      NPTR data;
      node* next;
      node (NPTR p) : data(p), next(0) {}
      };
      public:
      int count;
      node* getnode (NPTR p) { return new node(p); }
      node* listptr;
      void place (NPTR );
      NPTR mindelete();
      pq() : listptr(0), count(0) {}
  };
  
  void pq::place (NPTR p)
  {
      if(count == 0)
      {
          listptr = getnode(p);
      }
  
      else
      {
          node* foo = listptr, *bar = NULL;
          while( (foo!= NULL) &amp;&amp; (p-&gt;freq &gt;= foo-&gt;data-&gt;freq) )
          {
              bar = foo;
              foo = foo-&gt;next;
          }
          node* ptr = getnode(p);
          ptr-&gt;next = bar-&gt;next;
          bar-&gt;next = ptr;
      }
      ++count;
  }
  
  NPTR pq::mindelete()
  {
      if(count==0) { cout&lt;&lt;"invalid\n"; exit(1);}
      NPTR val = listptr-&gt;data;
      listptr = listptr-&gt;next;
      --count;
      return val;
  }
  
  void main ()
  {
      pq list;
      for ( int i=0; i&lt;3; ++i)
      {
          string s;
          int f;
          cin&gt;&gt;s&gt;&gt;f;
          NPTR p = new hnode(s,f);
          list.place(p);
      }
      while(list.count&gt;1)
      {
          NPTR p1 = list.mindelete();
          NPTR p2 = list.mindelete();
          hnode po = (*p1)+(*p2); // overloaded operator
          NPTR p = &amp;po;
          p-&gt;show();
          list.place(p);
      }
  }
  </code></pre>