資源簡介
哈夫曼編碼:從鍵盤輸入若干字符及每個字符出現的頻率,將字符出現的頻率作為結點的權值,建立哈夫曼樹,然后對各個字符進行哈夫曼編碼,最后打印輸出字符及對應的哈夫曼編碼。
代碼片段和文件信息
#include??
#include???
#define?N?10?/*待編碼字符的個數,即樹中葉結點的最大個數*/?
#define?M?2*N-1?/*樹中總的結點數目*/?
typedef?struct{?
int?weight;??
int?parentlchildrchild;??
}HTNode;?/*樹中結點的結構*/?
typedef?struct?{??
char?data;?/*待編碼的字符*/?
int?weight;?/*字符的權值*/?
char?code[N];?/*字符的編碼*/?
}?HTCode;??
void?Init(HTCode?hc[]int?*n){??/*初始化,讀入待編碼字符的個數n,從鍵盤輸入n個字符和n個權值*/?
int?i;?
printf(“please?input?the?number?of?code?which?is?to?be?encoded‘n‘(end?by?0):\n“);?
scanf(“%d“&(*n));?
if(*n!=0){??
printf(“input?%d?character\n“*n);getchar();?
for?(i=1;i<=*n;i++)
hc[i].data=getchar();?
printf(“input?%d?weight\n“*n);?
for?(i=1;i<=*n;i++)??
scanf(“%4d“&hc[i].weight);?
}?
}??
void?Select(HTNode?ht[]int?kint?*s1int?*s2){?
?/*ht[1?k]中選擇parent為0,并且weight最小的兩個結點其序號由指針變量s1s2指向*/?
int?i;??
for?(i=1;i<=k?&&?ht[i].parent!=0;i++);?
*s1=i;??
for?(i=1;i<=k;i++)??
if?(ht[i].parent==0?&&?ht[i].weight *s1=i;?
for?(i=1;?i<=k;i++)??
if?(ht[i].parent==0?&&?i!=*s1)?
break;?
*s2=i;??
for?(i=1;i<=k;i++)??
if?(?ht[i].parent==0?&&?i!=*s1?&&?ht[i].weight *s2=i;?
}??
void?huffman(HTNode?ht[]HTCode?hc[]int?n)
{?
int?ims1s2;?
m=2*n-1;??
for?(i=1;i<=m;i++){??
if?(i<=n)?ht[i].weight=hc[i].weight;?
else?ht[i].weight=0;??
ht[i].parent=
- 上一篇:B樹 C語言實現
- 下一篇:文件系統c語言實現,在linux下編譯
評論
共有 條評論