哈夫曼編碼實現文字壓縮

2021-10-09 14:59:44 字數 3649 閱讀 2254

由哈夫曼樹的定義可知,初始森林中共有n棵只含有根結點的二叉樹,將當前森林中的兩棵根結點權值最小的二叉樹合併成一棵新的二叉樹;每合併一次,森林中就減少一棵樹,產生乙個新結點。顯然要進行n-1次合併,所以共產生n-1個新結點,它們都是具有兩個孩子的分支結點。由此可知,最終求得的哈夫曼樹中一共有2n-1個結點,其中n個結點是初始森林的n個孤立結點。並且哈夫曼樹中沒有度數為1的分支結點。可以利用乙個大小為2n-1的一維陣列來儲存哈夫曼樹中的結點。

定義結構體型別

char hmfcode[max]

;typedef

struct

htnode;

根據設計要求和實際需要定義的型別如下:

typedef

struct

hcode;

字元數統計函式:

int

statistics

(char

*s,int cnt,

char str)

j=0;for

(i=1

,j=0

; i<=

256; i++)if

(cnt[i]!=0

)return j;

}

哈夫曼樹建立函式:

void

createht

(htnode ht,

int n,

char str,

int cn)

int l=0;

for(

int output=

1; output<=

256; output++)}

int i,k,lnode,rnode;

int min1,min2;

for(i=

0; i<

2*n-

1; i++

) ht[i]

.parent=ht[i]

.lchild=ht[i]

.rchild=0;

//所有結點的相關域置初值 0

for(i=n; i<

2*n-

1; i++

)else

if(ht[k]

.weight

ht[lnode]

.parent=i;

ht[rnode]

.parent=i;

//兩個最小節點的父節點是 i

ht[i]

.weight=ht[lnode]

.weight+ht[rnode]

.weight;

//兩個最小節點的父節點權值為兩個最小節點權值之和

ht[i]

.lchild=lnode;

ht[i]

.rchild=rnode;

//父節點的左節點和右節點

}}

根據哈夫曼樹求哈夫曼編碼:

void

createhcode

(htnode ht[

],hcode hcd,

int n)

hc.start++

;//start 指向哈夫曼編碼 hc.cd 中最開始字元

hcd[i]

=hc;

}}

輸出哈夫曼編碼的列表:

void

outputhcode

(htnode ht[

],hcode hcd,

int n)

printf

("\n");

}}

編碼函式,將編碼結果存入檔案hmfcode.txt中:

void

edithcode

(htnode ht[

],hcode hcd,

int n,

char str)

break

;//輸出完成後跳出當前 for 迴圈

}fputc

('\n'

, fp)

;printf

("\n");

fclose

(fp)

;}

解碼函式(解壓函式),將解碼結果存入檔案hmfcode.txt中:

void

dehcode

(htnode ht[

],hcode hcd,

int n,

char str)

break

;//輸出完成後跳出當前 for 迴圈

} code[m]

='#'

;//把要進行解碼的字串存入 code 陣列中

while

(code[0]

!='#'

)for

(i=0

; i(m==j)}}

fputc

('\n'

, fp)

;printf

("\n");

fclose

(fp)

;}

主函式

#include

#include

//gets()函式需要

#define n 256

//用 n 表示 50 葉節點數

#define m 2*n-1

//用 m 表示節點總數 當葉節點數字 n 時總節點數為 2n-1

#define max 32767

intmain()

else

n=statistics

(st,cn,sst)

;for

(i=0

; i<

99; i++

) sst[i]

=st[i]

; htnode ht[m]

; hcode hcd[n]

;createht

(ht,n,st,cn)

;createhcode

(ht,hcd,n)

;outputhcode

(ht,hcd,n)

;edithcode

(ht,hcd,n,sst)

;dehcode

(ht,hcd,n,sst)

;printf

("結果已成功儲存在檔案hmfcode.txt中!");

fclose

(fp)

;}

輸入字串,實現編碼,解碼並將結果寫入檔案hmfcode.txt中:

從檔案text.txt讀取內容,實現編碼,解碼並將結果寫入檔案hmfcode.txt中:

哈夫曼樹和哈夫曼編碼(檔案壓縮)

哈夫曼樹 huffman tree 帶權路徑長度 wpl 設二叉樹有n個葉子結點,每個葉子結點帶有權值wk,從根節點到每個葉子結點的長度為lk,則每個葉子結點帶權路徑長度之和就是 wk lk 求和 最優二叉樹或哈夫曼樹 wpl最小的二叉樹 哈夫曼樹的構造 每次把權值最小的兩棵二叉樹合併 1 huff...

哈夫曼編碼實現

define huffmancode char typedef struct node huffmantree struct node 葉節點為n的哈夫曼樹有2 n 1個節點 用 1表示當前parent未被訪問 huffmantree createhuffmantree int wet,int n ...

實現哈夫曼編碼

include include include include include using namespace std typedef struct node vector nodes 表示結點的指標組 double char number 0 每個字元平均花費的編碼長度 const int cha...