C語言實現哈夫曼編碼

2021-07-25 22:49:46 字數 1319 閱讀 4746

#include

#define n5 //葉子數目

#define m(2*n-1) //結點總數

#define maxval 10000.0

#define maxsize100 //哈夫曼編碼的最大位數

typedef struct

hufmtree;

typedef struct

codetype;

void huffman(hufmtree tree);//建立哈夫曼樹

void huffmancode(codetype code,hufmtreetree);//根據哈夫曼樹求出哈夫曼編碼

void decode(hufmtree tree);//依次讀入電文,根據哈夫曼樹解碼

void main()

printf("【讀入電文,並進行解碼】\n");

decode(tree);//依次讀入電文,根據哈夫曼樹解碼

}void huffman(hufmtree tree)//建立哈夫曼樹

printf("【依次讀入前%d個結點的字元及權值(中間用空格隔開)】\n",n);

for(i=0;i //讀入前n個結點的字元及權值

for(i=n;i //進行n-1次合併,產生n-1個新結點

else

if(tree[j].weight

tree[p1].parent=i;

tree[p2].parent=i;

tree[i].lchild=p1; //最小權根結點是新結點的左孩子

tree[i].rchild=p2; //次小權根結點是新結點的右孩子

tree[i].weight=tree[p1].weight+tree[p2].weight;

}}//huffman

void huffmancode(codetype code,hufmtreetree)//根據哈夫曼樹求出哈夫曼編碼

//codetype code為求出的哈夫曼編碼

//hufmtree tree為已知的哈夫曼樹

code[i]=cd; //第i+1個字元的編碼存入code[i]

}}//huffmancode

void decode(hufmtree tree)//依次讀入電文,根據哈夫曼樹解碼

j++;

} printf("\n");

if(tree[i].lchild!=-1&&b[j]!='2') //電文讀完,但尚未到葉子結點

printf("\nerror\n"); //輸入電文有錯

}//decode

哈夫曼編碼 C語言實現

c語言實現哈夫曼編碼 程式功能 提供一段字串,輸出哈夫曼編碼壓縮後的總位元數 計入小寫字母和空格 include include 定義二叉樹結構 typedef struct node bitnode,bitree 定義棧結構,此處的棧用來儲存二叉樹節點 typedef structstack 操作...

C語言實現哈夫曼編碼

include include define n 50 葉子結點數 define m 2 n 1 樹中結點總數 typedef struct htnode typedef struct hcode void createht htnode ht,int n 由ht的葉子結點構造完整的哈夫曼樹 els...

哈夫曼樹編碼C語言實現

哈夫曼樹編碼c語言實現,實現哈夫曼樹編碼的演算法可分為兩大部分 1 構造哈夫曼樹 2 在哈夫曼樹上求葉結點的編碼 哈夫曼樹構造演算法 1 由給定的n個權值構造n棵只有乙個葉結點的二叉樹,從而得到乙個二叉樹的集合f 2 在f中選取根結點的權值最小和次小的兩棵二叉樹作為左,右子樹構造一棵新的二叉樹,這棵...