[英]huffman algorithm
我正在HUFFMAN 算法上編寫一個程序,其中有一類節點( hnode )包含符號( 名稱 )及其出現頻率( freq )。 和其他類( pq ),用於形成樹以獲取符號的代碼。 我只寫了課程的相關部分。 現在,當我嘗試運行該程序時,當它第二次進入while循環時,它總是卡在while循環中( 在main()中 )。 我已經嘗試了所有方法,但是仍然不知道為什么...有人可以幫忙使這段代碼運行!
#define NPTR hnode*
class pq;
class hnode
{
string name;
int freq;
friend class pq;
public:
NPTR phnode;
void show ()
{ cout << "name = " << name << endl << ", freq= " << freq <<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) && (p->freq >= foo->data->freq) )
{
bar = foo;
foo = foo->next;
}
node* ptr = getnode(p);
ptr->next = bar->next;
bar->next = ptr;
}
++count;
}
NPTR pq::mindelete()
{
if(count==0) { cout<<"invalid\n"; exit(1);}
NPTR val = listptr->data;
listptr = listptr->next;
--count;
return val;
}
void main ()
{
pq list;
for ( int i=0; i<3; ++i)
{
string s;
int f;
cin>>s>>f;
NPTR p = new hnode(s,f);
list.place(p);
}
while(list.count>1)
{
NPTR p1 = list.mindelete();
NPTR p2 = list.mindelete();
hnode po = (*p1)+(*p2); // overloaded operator
NPTR p = &po;
p->show();
list.place(p);
}
}
您的代碼在此處創建了本地范圍的hnode po
:
while(list.count > 1)
{
NPTR p1 = list.mindelete();
NPTR p2 = list.mindelete();
hnode po = (*p1)+(*p2); // overloaded operator
NPTR p = &po;
p->show();
list.place(p);
}
然后按地址傳遞它,並使pq::node
保持住該地址。 聽起來真是個壞主意,因為hnode po
在每次迭代的while循環結束時超出范圍 。
通常,您希望將智能點和RAII用於自動內存管理,而不是在各處進行“添加和刪除”操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.