Huffman樹的編碼解碼

2022-03-31 13:20:31 字數 2737 閱讀 6555

上個學期做的課程設計,關於huffman樹的編碼解碼。

要求:輸入huffman樹各個葉結點的字元和權值,建立huffman樹並執行編碼操作

輸入一行僅由01組成的電文字串,根據建立的huffman樹進行解碼操作,程式最後輸出解碼後的結果

huffman.h定義了樹的結點資訊,各種操作。gcc編譯通過。

1

#ifndef huffman_h_included

2#define huffman_h_included

3 #include 4 #include 5 #include 67

#define leafnumber 20

8#define totalnumber 39

9#define maxvalue 100

10using

namespace

std;

1112

//權值型別, 這裡定義為int

13 typedef int

wtype;

1415

//樹的結點型別, 這裡定義為char, 表示字元

16 typedef char

telemtype;

1718

//huffman樹結點資訊定義

19 typedef struct

huffmannode;

2728

//huffman樹結構定義

29 typedef struct

huffmantree;

3334

/*35

*構建huffman樹

36*/

37void createhuffmantree( huffmantree &ht, wtype w, int

n )

52else

if( ht.elem[j].weight

57 ht.elem[i].left_child =p1;

58 ht.elem[i].right_child =p2;

59 ht.elem[i].weight = ht.elem[p1].weight +ht.elem[p2].weight;

60 ht.elem[p1].parent = ht.elem[p2].parent =i;61}

62 ht.currentnumber = 2 * n - 1;63

}6465/*

66*對huffman樹每個結點進行編碼

67*/

68void coding( huffmantree &ht, int

n )

85if( ht.elem[parent].right_child == current ) 89}

90*/

9192

93while (parent != -1)94

101102

+= "0";

103reverse( ht.elem[i].code.begin(), ht.elem[i].code.end() );

104105

}106

107}

108109

/*110

*解碼111

*/112

void decode( huffmantree &ht, int

n )

130else

if( ch[i] == '1'

) 136

if( ht.elem[index].left_child == -1 && ht.elem[index].right_child == -1

) 143 i++;

144}

145}

146/*

147*遍歷

148*/

149void preorder( huffmantree &ht, int

n )

153};

154155

156#endif

//huffman_h_included

#include "

huffman.h

"int

main() ;

//wtype weight = ;

createhuffmantree( ht, weight, 5

); coding( ht, 5);

preorder( ht, 5);

cout

<< endl <

for( int i = 0; i < 9; i++)

cout

<< "

node

"<< i << "

code:

"<< ht.elem[i].code <

cout

<< endl <

for( int i = 0; i < 9; i++)

decode( ht, 5);

return0;

}

執行截圖:

Huffman樹進行編碼和解碼

編碼 include include include include include include include include using namespace std typedef struct huffmannode huffmannode,phuffmannode typedef pai...

Huffman編碼與解碼

近期學習資料結構碰到huffman編碼與解碼問題,自己動手寫了一些,注釋比較全,ok,下面直接貼 include include define telemtype char define wtype int define leafnumber 5 預設權重集合大小 define totalnumbe...

huffman編碼和解碼實現

寫資料結構的實驗確實是蠻麻煩的,下面提供乙個還可以執行的源程式給大家參考,應付實驗老師是綽綽有餘的了 link.h檔案內容 pragma once class link link的實現檔案什麼內容也沒有,所以就不寫啦 huffman.h內容 pragma once include link.h cl...