哈夫曼编码的优点(哈夫曼编码)
大家好,我是小十,我来为大家解答以上问题。哈夫曼编码的优点,哈夫曼编码很多人还不知道,现在让我们一起来看看吧!
1、
1、#include<iostream>
2、using namespace std;
3、int co[100];
4、typedef struct node
5、{
6、 int data;
7、 char ch;
8、 struct node *left,*right;
9、 struct node *next;
10、}Bnode;
11、void insert(Bnode *L,char ch,int num)
12、{
13、 Bnode *p,*q;
14、 p=L;
15、 while(p->next)
16、 {
17、 if (num>=p->next->data)
18、 p=p->next;
19、 else break;
20、 }
21、 q=new Bnode;
22、 q->data=num;
23、 q->ch=ch;
24、 q->left = q->right = NULL;
25、 q->next=p->next;
26、 p->next=q;
27、}
28、//插入结点
29、void insert_nod(Bnode *L,Bnode *q)
30、{
31、 Bnode *p;
32、 p=L;
33、 while(p->next)
34、 {
35、 if (q->data>=p->next->data)
36、 p=p->next;
37、 else break;
38、 }
39、 q->next = p->next ;
40、 p->next = q;
41、}
42、//编码
43、void code(Bnode *L,int i)
44、{
45、 int j;
46、 if (!L->left&&!L->right)
47、 {
48、 for(j=0;j<=i-1;j++)
49、 cout<<co[j];
50、 cout<<endl;
51、 }
52、 if (L->left)
53、 {
54、 co[i]=0;
55、 code(L->left,i+1);
56、 }
57、 if (L->right)
58、 {
59、 co[i]=1;
60、 code(L->right,i+1);
61、 }
62、
63、
64、}
65、void main()
66、{
67、 FILE *fp;
68、 int n,i;
69、 char ch,*charra;
70、 int *numarra;
71、 Bnode *p1,*p2,*q;
72、 Bnode *L=new Bnode;
73、 L->data=0;
74、 L->next=NULL;
75、 scanf("%d",&n);
76、 scanf("%c",&ch);
77、 charra=new char[n];
78、 numarra=new int[n];
79、 for(i=0;i<n;i++)
80、 {
81、 scanf("%c",&charra[i]);
82、 }
83、 for(i=0;i<n;i++)
84、 {
85、 scanf("%d",&numarra[i]);
86、 }
87、 for(i=0;i<n;i++)
88、 {
89、 insert(L,charra[i],numarra[i]);
90、 }
91、 for(i=1;i<n;i++)
92、 {
93、 p1=L->next ;
94、 p2=p1->next ;
95、 L->next = p2->next ;
96、 q=new Bnode;
97、 q->left = p1;
98、 q->right = p2;
99、 q->data = p1->data +p2->data;
100、 q->next = NULL;
101、 insert_nod(L,q);
102、 }
103、 code(L->next,0);
104、}
本文到此讲解完毕了,希望对大家有帮助。