"Data structure" Huffman Tree Implementation coding decoding

Source: Internet
Author: User


A Huffman tree is generated based on the number of characters in a string as the weight of the character.

Then according to the generated Huffman code, the arbitrary string Implementation code, the arbitrary binary string implementation decoding.

Program Run Result:


1. Program Main interface:


2. Create Huffman tree and encodings based on the string:


3. The resulting encoding table is as follows:


4. Encode the string according to the generated Huffman code:


5. The generated encoding is saved in the file:


6. Decoding the binary string:



Results:





Code:

Huffman Tree generation and coding of common, as well as encoding and decoding functions

_huffmantree_h#ifndef _huffmantree_h#define _huffmantree_htypedef struct {   unsigned int weight;   char ch;   unsigned int parent,lchild,rchild;} Htnode,*huffmantree;  typedef char **huffmancode; These three are Huffman tree generation int min1 (huffmantree t,int i);     Select the smallest of the weights array, void Select (Huffmantree t,int i,int *s1,int *s2);   The smallest of the two weights in the array, and change the temporary array corresponding position to 1 to prevent the repetition of the selection void huffmancoding (Huffmantree *ht,huffmancode *hc,int *w,int N);  According to the weights array w, and the number of elements n to open up space, HC storage code void getweightinfile (int *w);//read letters from MyTxt.TXT, use the number of letters as weights, generate an array and return void Bianmainfile ( Huffmantree *p,huffmancode CD);    According to the encoded. txt inside letter, find the corresponding subscript, in HC inside matching code void Yimainfile (Huffmantree *p);   The  root node of the analysis of the number of the subscript should be 2n-1 ... So just follow the code 0 1 to determine left or right end until = encounter meaningful letter stop #endif  //

Read and write to the specified file

Myfile.h#ifndef _myfile_h#define _myfile_h#define My_strmax 100void changmytxtfile (); void Showmytxtfile (); void Showbianmafile (); void Showyimafile (); void Changbianmafile (); #endif   //myfile.h

Huffmantree.c#include <stdio.h> #include <stdlib.h> #include <string.h> #include "HuffmanTree.h" int min1 (Huffmantree t,int i) {/* Returns the root node ordinal of the tree with the lowest weight in the I node, the function Select () calls */int j,flag;unsigned int k=10000000;/* takes K to be no less than possible (no character Number integer maximum) */for (j=1;j<=i;j++) if (t[j].weight<k&&t[j].parent==0)//T[j] is the root node of the tree */k=t[j].weight,flag=j;t[ Flag].parent=1; /* Assign 1 to the parent of the selected root node to avoid finding the node */return flag for the 2nd time; }void Select (Huffmantree t,int i,int *s1,int *s2) {/* Selects the root node ordinal of the tree with the least 2 weights in the I node, S1 the one with the smaller sequence number, */int j;*s1=min1 (t,i); *s2=min1 (t,i); if (*s1>*s2) {j=*s1;*s1=*s2;*s2=j;}} void Huffmancoding (Huffmantree *ht,huffmancode *hc,int *w,int N)/* Algorithm 6.12 */{/w holds weights of n characters (all >0), constructs Huffman Tree HT, and find the n characters of Huffman encoded HC */int m,i,s1,s2,start,num=0;unsigned c,f;    Huffmantree P;char *cd;if (n<=1) return;m=2*n-1; The space opened up is more than the number of elements because the subsequent generation of new subtrees is used to *ht= (Huffmantree) malloc ((m+1) *sizeof (Htnode)); /* Unit No. 0 is not used */for (p=*ht+1,i=1;i<=n;++i,++p,++w,++num) {(*p). weight=*w;//This section is assigned to the defined subtree, including the letter A-Z weights from the array to derive if (i<26) ( *P). Ch=97+num;else If(i==26) {(*p). Ch=97+num;num=-1;} else if (i<=52&&i>26) (*p). Ch=65+num;else if (i==53) (*p). Ch=32;else if (i==54) (*p). ch= ' \ n ';(*p). parent= 0; (*p). Lchild=0; (*p). Rchild=0;} for (; i<=m;++i,++p) (*p). Parent=0;for (I=n+1;i<=m;++i)//Kenkheffman tree */{/* in ht[1~i-1] Select two nodes with a parent of 0 and a minimum of weight,     The serial numbers are S1 and S2 */select (*HT,I-1,&AMP;S1,&AMP;S2);(*ht) [S1].parent= (*HT)] [s2].parent=i;                        This section gives the new node initial value (*HT) [I].lchild=s1; (*HT) [I].rchild=s2; (*HT)] [i].ch= '! ';   They're storing it! So you can tell if this node makes sense (*HT) [I].weight= (*HT) [s1].weight+ (*HT) [S2].weight;} Huffman codes are saved in HC (two-dimensional array)/* Huffman encoding */*hc= (Huffmancode) malloc ((n+1) *sizeof (char*)) for each character from the leaf to the root, and/* assigns a N-character encoded head-pointer vector ([0] NO) */cd= (char*) malloc (n*sizeof (char)); /* Allocate a working space for coding */cd[n-1]= ' + '; /* Encoding Terminator */for (i=1;i<=n;i++) {/* character Fu Tiuhe */start=n-1;/* encoding Terminator position */for (c=i,f= (*HT) [i].parent;f!=0;c=f,f= (*HT) [F] . Parent)/* from leaf to root reverse coding */if ((*HT) [f].lchild==c) cd[--start]= ' 0 '; elsecd[--start]= ' 1 ';(*hc) [i]= (char*) malloc (( N-start) *sizeof (char));/* Allocates space for the I-character encoding */strCPY ((*HC) [I],&cd[start]); /* Copy the Encoding (string) from the CD to the HC */}free (CD); /* Free workspace */}void getweightinfile (int *w) {file *pfr;int I=0;PFR = fopen ("Record Information \\mytxt.txt", "R");//Read file if (pfr==null) {p rintf ("File operation failed"); return;} Else{while (!feof (PFR))//until the file is read, read one line at a time {char str[256] = {0};fgets (str, n, PFR);//read one line I=0;while (str[i]!=0)//if this is a letter, then the corresponding array from 0-25 found a corresponding value Gaga implementation of the number of letters in the calculation file {if (str[i]<= ' z ' && str[i]>= ' a ')//97-122 65-90 32w[str[i] -97]++;if (str[i]<= ' Z ' && str[i]>= ' A ') w[str[i]-65+26]++;if (str[i]== ") w[26*2]++;if (str[i]== ' \ n ') w[ 26*2+1]++;i++;}}}                    Fclose (PFR);} File runs out to close void Bianmainfile (Huffmantree *p,huffmancode cd) {file *PFR; File *pfw;//huffmantree ptr= (*p) +1;int i;int num;int COUNT=1;PFR = fopen ("Record Information \\mytxt.txt", "R");//Read files PFW = fopen ("Log information \ \ encoded. txt "," w ");//write file if (Pfr==null | | pfw==null) {printf (" File operation failed "); return;} else {while (!feof (PFR)) {char str[256] = {0};fgets (str, n, PFR);//reads a row of I=0;num=-1;while (str[i]!=0) {if (str[i]<=122 &&amp str[i]>=97)//1-26num=str[i]-96;else if (str[i]<=90 && str[i]>=65)//27-52num=str[i]-64+26;else if (s TR[I]==32) Num=53;else if (str[i]== ' \ n ') num=54;if (num!=-1)//The Code inside the CD is output to the encoded. txt {if (count==1) count++;else//fputs ( Cd[num], PFW); fprintf (PFW, "%s\n", Cd[num]);} I++;num=-1;}} Fclose (PFR); fclose (PFW);}} void Yimainfile (Huffmantree *p) {FILE *PFR;  FILE *pfw;char S[2]={0};int i=0,num=107; 51=2*26-1 2*54-1int N;PFR = fopen ("Record information \ \ encoded. txt", "R");//Read File PFW = fopen ("Record information \ \ decode. txt", "w");//write file if (Pfr==null | | p Fw==null) {printf ("File operation failed"); return;} else {while (!feof (PFR)) {char str[255] = {0};fgets (str, 255, PFR); i=0;//reads one line num=107;while (str[i]!=0) {n=i;while (Str[i]            !=0) {if ((*p) [num].ch!= '! ') If found left and right move found the letter immediately exit match next break;if (str[i]== ' 0 ')//0 Left 1 R num= (*p) [Num].lchild;else if (str[i]== ' 1 ') num= (*p) [n um].rchild;i++;} if ((*p) [num].ch== '! ' && str[i]!= ') printf ("Because the encoding is not complete,%d-%d code is dropped \ n", n+1,i); else if (str[i]!= '} ') {s[0]= (*p) [Num].ch;fputs (S, PFW);} num=107;}}} Fclose (PFR); fclose (PFW);}

Myfile.c#include <stdlib.h> #include <stdio.h> #include "myfile.h" #include <conio.h>void Changmytxtfile () {file *pfw;int s;int num=1;pfw=fopen ("Record Information \\mytxt.txt", "w"), if (pfw==null) {printf ("File operation failed"); return ;} while (S=getchar (), s!=-1) {fprintf (PFW, "%c", s);} Fclose (PFW);} void Showmytxtfile () {file *pfr;pfr=fopen ("Record Information \\mytxt.txt", "R"), if (pfr==null) {printf ("File operation failed"), return;          else {while (!feof (PFR)) {char str[256] = {0};fgets (str, n, PFR); Dynamically traverse file puts (str);}} Fclose (PFR);} void Showbianmafile () {file *pfr;pfr=fopen ("record information \ \ encoded. txt", "R"), if (pfr==null) {printf ("File operation failed"), return; else {while (!feof (PFR)) {char str[256] = {0};fgets (str, n, PFR);p UTS (str);}} Fclose (PFR);} void Showyimafile () {file *pfr;pfr=fopen ("record information \ \ decode. txt", "R"), if (pfr==null) {printf ("File operation failed"); return;} else {while (!feof (PFR)) {char str[256] = {0};fgets (str, n, PFR);p UTS (str);}} Fclose (PFR);} void Changbianmafile () {file *pfw;int s;pfw=fopen ("record information \ \ encoded. txt", "w"), if (pfw==null) {printf ("Record information \ \ File operation failed");while (S=getchar (), s!=-1) {fprintf (PFW, "%c", s);} Fclose (PFW);}

Main.c#include <stdlib. H> #include <stdio.   h> #include "HuffmanTree.h" #include "myfile.h" #define Myhfmnum 26*2+2int Main () {Huffmantree HT;   Huffmancode HC;   int w[myhfmnum]={0},n=myhfmnum,i;   Char s[my_strmax]={0};    int Num;system ("color 3e");   Change the color Menu:system ("CLS");   Puts ("***********************************************");   Puts ("1. Create a new Code");   Puts ("2. Code");   Puts ("3. Decoding");   Puts ("4. Exit");   Puts ("***********************************************");       Puts ("Enter the desired action:");   scanf ("%d", &num);   Switch (num) {Case 1: {FILE *pfw; System ("CLS");   Each operation cleans up the screen puts ("Enter a string that accumulates weights based on the number of characters, resulting in a tree");   Changmytxtfile ();   Getweightinfile (w);   Huffmancoding (&ht,&hc,w,n);   Pfw=fopen ("record information \ \ Code table. txt", "w");   if (pfw==null) {printf ("File operation failed"); return 0;}     fprintf (PFW, "coded letter weights \ n"); for (i=1;i<=n;i++)//Put the generated encoding table in the file for easy comparison with {fprintf (PFW, "%10s\t%c\t%2d\n", Hc[i],ht[i].ch,ht[i].weight      ); } fclose (PFW); System ("PauSe ");   Goto MENU;   } Case 2: {System ("CLS");   Puts ("Enter the string to encode");   Changmytxtfile ();    Bianmainfile (&AMP;HT,HC);   Showbianmafile ();   System ("pause");   Goto MENU;   } Case 3:{system ("CLS");   Puts ("Input binary number to decode");   Changbianmafile ();   Yimainfile (&AMP;HT);    Showyimafile (); System ("pause");   Pause for a moment equivalent to Getch goto MENU;   } case 4:return 0; Default:puts ("Wrong input!");              System ("pause"); goto MENU; } return 0;}


"Data structure" Huffman Tree Implementation coding decoding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.