1. This program is a C ++ program.
2. The following code can be entered manually, that is, remove the/*... */annotator in the Code and remove the value assignment code segment.
3. Source Code
# Include <iostream>
Using namespace STD;
Typedef struct
{
Int weight, parent, lchild, rchild;
} Htnode, * huffmantree;
Typedef char ** huffmancode;
Typedef struct
{
Int weight, locate;
} Tnode, * temp;
Void creathuffmantree (huffmantree & HT, int N );
Void creathuffmancode (huffmantree HT, huffmancode & HC, int N );
Int main ()
{
Huffmantree HT;
Huffmancode HC;
Int n = 8;
Char P = 'y ';
While (P = 'y ')
{
/* Cout <"Enter the number of data to be encoded :";
Cin> N ;*/
Creathuffmantree (HT, N );
Creathuffmancode (HT, HC, N );
Cout <"Enter y for re-execution, and enter N for non-execution" <Endl;
Cin> P;
}
System ("pause ");
Return 0;
}
// Generate the user tree
Void creathuffmantree (huffmantree & HT, int N)
{
Int I, J, K, S1, S2, num;
Ht = new htnode [2 * n];
For (I = 1; I <2 * n; I ++)
{
HT [I]. Parent = 0;
HT [I]. lchild = 0;
HT [I]. rchild = 0;
}
/* Cout <"Enter data :";
For (I = 1; I <= N; I ++)
{
Cin> HT [I]. weight;
}*/
HT [1]. Weight = 5;
HT [2]. Weight = 29;
HT [3]. Weight = 7;
HT [4]. Weight = 8;
HT [5]. Weight = 14;
HT [6]. Weight = 23;
HT [7]. Weight = 3;
HT [8]. Weight = 11;
For (I = n + 1; I <2 * n; I ++)
{
// From 1 ~ The subscript of the node with the smallest weight is selected in the I-1.
// Statistics 1 ~ Number of zero-parent nodes in the I-1
Num = 0;
For (k = 1; k <I; k ++)
{
If (HT [K]. Parent = 0)
{
Num ++;
}
}
// Store the weights and subscripts of the zero-parent nodes into a new struct array.
Temp T;
T = new tnode [num];
For (j = 0, k = 1; k <I; k ++)
{
If (HT [K]. Parent = 0)
{
T [J]. Weight = HT [K]. weight;
T [J]. Locate = K;
J ++;
}
}
// Select sorting
For (j = 0; j <num-1; j ++)
{
For (k = J + 1; k <num; k ++)
{
If (T [J]. weight> T [K]. Weight)
{
Tnode temp;
Temp = T [k];
T [k] = T [J];
T [J] = temp;
}
}
}
S1 = T [0]. Locate;
S2 = T [1]. Locate; // select subscript to end
HT [S1]. Parent = I;
HT [s2]. Parent = I;
HT [I]. lchild = S1;
HT [I]. rchild = S2;
HT [I]. Weight = HT [S1]. Weight + HT [s2]. weight;
Delete T;
}
Cout <"Harman tree:" <Endl;
For (I = 1; I <2 * n; I ++)
{
Cout <HT [I]. weight <'\ t' <HT [I]. parent <'\ t' <HT [I]. lchild <'\ t' <HT [I]. rchild <Endl;
}
}
// Harman Encoding
Void creathuffmancode (huffmantree HT, huffmancode & HC, int N)
{
Int I, C, F, start;
Char * CD;
Hc = new char * [n + 1];
Cd = new char [N];
CD [n-1] = '\ 0 ';
For (I = 1; I <= N; I ++)
{
Start = n-1;
C = I;
F = HT [I]. parent;
While (F! = 0)
{
Start --;
If (HT [f]. lchild = C)
{
CD [start] = '0 ';
}
Else
{
CD [start] = '1 ';
}
C = F;
F = HT [f]. parent;
}
HC [I] = new char [n-start];
Strcpy_s (HC [I], n + 1, & CD [start]);
}
Delete CD;
Cout <"husky Code :";
For (I = 1; I <= N; I ++)
{
Cout <HC [I];
}
Cout <Endl;
}