我用链表的形式实现赫夫曼树,但程序出错了,不会改,求大佬解决!
#include
using namespace std;
typedef struct HTNode{ int weight; struct HTNode *parent, *lchild, *rchild; }HTNode, *HuffmanTree;
typedef struct { HTNode *base; int front; int rear;}SqQueue;
void InitHuffmanTree(HuffmanTree &t) {
t = new HTNode;
t->parent = NULL;
t->lchild = NULL;
t->rchild = NULL;}
void InitQueue(SqQueue &S) {
S.base = new HTNode[100];
S.front = S.rear = 0;
}
void enter(SqQueue &S) {
int a = 0; int c = 0;
cout << “输入权的个数:” << endl; cin >> a; for (int i = 0; i < a; i++) { cout<<“输入权值:”<<endl; cin >> c; S.base[S.rear].weight = c; S.base[S.rear].parent = NULL; S.base[S.rear].lchild = NULL; S.base[S.rear].rchild = NULL; S.rear++;
}
cout << “存储权值完毕!” << endl;}
void Push(SqQueue &S,HTNode n){
S.base[S.rear++] = n;
}
HTNode Popelem(SqQueue &S){
HTNode e;
e = S.base[S.front++];
return e;}
void QueueSort(SqQueue &S){
int i, j,temp;
for(i=0;i<S.rear-1;i++)
for (j = 1; j < S.rear; j++)
{ if (S.base[i].weight > S.base[j].weight) { temp = S.base[i].weight; S.base[i].weight = S.base[j].weight; S.base[j].weight = temp; } }
cout << “排序完毕!” << endl;}
void CreatTree(HuffmanTree &t, SqQueue &S){
HuffmanTree p;
p = t;
while (S.front < S.rear-1)
{ HTNode a, b, c; a = Popelem(S); b = Popelem(S);
c.weight = a.weight + b.weight;
a.parent = &c;
b.parent = &c;
c.lchild = &a;
c.rchild = &b;
Push(S,c);
QueueSort(S); }
t = &Popelem(S);}
void PostOrderTraverse(HuffmanTree &t){
if (t) {
PostOrderTraverse(t->lchild); PostOrderTraverse(t->rchild);
cout << t->weight << " "; } }
int main(){
HuffmanTree T;
SqQueue s;
InitHuffmanTree(T);
InitQueue(s);
enter(s);
CreatTree(T, s);
PostOrderTraverse(T);
return 0;}