Message encoding and decoding (application of Huffman tree) __ Code

Source: Internet
Author: User


First, the experimental environment

Learn treasure virtual machine, VC6.0

Ii. purpose of the experiment

From the keyboard to receive a string of characters, the output of the corresponding Huffman code, at the same time can translate Huffman coding generated code string, output corresponding to the text character.

Iii. contents of the experiment

1. Use C language to realize the chain of two fork tree (binary chain table) storage structure;

2. To achieve the basic operation of the two Fork tree related algorithms (the establishment of binary tree, all kinds of traversal, etc.);

3. Define the static chain of binary tree structure, and use this structure to store Huffman tree, using Huffman tree to solve the coding and decoding of the actual application problems.

IV. data structure and algorithm idea description

(1) Establishment of Huffman tree:

If the "weight value" of the occurrence probability of n characters is known, the Huffman Tree with 2n-1 nodes (static linked list storage structure) is constructed.

(2) Code:

From the leaf node of Huffman tree, through parents find h[f], through the left child and the right child of h[f to determine whether the leaf is left branch or right branch. If it is to the right, it is ' 1 '. On the contrary, ' 0 '. Put in the array Cd[start], repeat the process until you find the root. The encoded value of the array in reverse output.

(3) Decoding:

Step 1: Design a loop structure to receive user input binary code into CH[1..M], each loop receives a "0" or "1" at the same time to record the length of the code, and finally the length into m, set K pointer to the initial value = 1;

Step 2: Point the F pointer to the root node. Using pointer k to scan to binary code ch[] the K-bit, if the current K-bit binary number ch[k] = "0" then f to its left child movement, if the ch[k]= "1", then f to its right child to move; F perform a k++ every step of the move until the left child (or right child) of F is found to be "empty" The F encounters the leaf node and prints the value stored in the data of the leaf node of F;

Step 3: When K<=m, then go to step 2, continue to scan the remaining digits in the binary code, otherwise the decoding completes, print the return character and then end the program.


#include <stdio.h> typedef struct {  CHAR data   int w,l,r,p;}
Node typedef struct{&NBSP;CHAR CD[50];  int start;
Code int Create (node *h) {  int i,k,n,m1,m2,p1,p2   printf ("Please enter the number of elements:");   scanf ("%d", &n);   for (I=1; i<n+1;i++) {    getchar ()     printf ("node values and weights for%d elements:", i);     scanf
("%c%d", &AMP;H[I].DATA,&AMP;H[I].W);
 }   for (i=1;i<=2*n-1;i++)       h[i].p=h[i].l=h[i].r=0;
  for (i=n+1;i<=2*n-1;i++) {      m1=m2=32767       p1=p2=i;       for (k=1;k<i;k++) {          if (h[k].p==0) {               if (h[k].w<m1) {        
         m2=m1;
                 P2=P1;                  M1=H[K].W;
                 p1=k;              }            & nbsp;  else if (h[k].w<m2) {                
  M2=H[K].W;
                  p2=k;              }          }  
    }       h[p1].p=i;
      h[p2].p=i;
      h[i].w=m1+m2;
      H[i].l=p1;
      h[i].r=p2;
 }   printf ("Success for hufftree!\n");
  return n; } void Encoding (node H[],code co[],int N) {     code D;      int I,K,f,c;      for (i=1;i<n+1;i++) {         d.start=n+1;   
      c=i;
         F=H[I].P;          while (f!=0) {          ,   if (h[f].
L==C)                   d.cd[--d.start]= ' 0 ';
              else  d.cd[--d.start]= ' 1 ';
              c=f;
              f=h[f].p;                      }     &
nbsp;    Co[i]=d;
    }      printf ("Output Huffman code: \ n");      for (i=1;i<=n;i++) {         printf ("%c:", h[I].data);          for (k=co[i].start;k<=n;k++) {         
    printf ("%c", Co[i].cd[k]);
        }          printf ("\ n");     } void decoding (node H[],code co[],int n) {   int f,m,k;    Char c,ch[200]; &nbs
p;  printf ("Please output message (0 or 1), with ' # ' for end sign: \ n");
   C=getchar ();
   k=1;    while (c!= ' # ') {      ch[k]=c       C=getchar ();  
     k++;
  }    m=k;
   f=2*n-1;
   k=1;
   printf ("Output Huffman code: \ n");    while (k<m) {       while (h[f].l!=0) {      
    if (ch[k]== ' 0 ') f=h[f].l;
           if (ch[k]== ' 1 ') F=H[F].R;        &NBSP;&Nbsp;  k++;
      }        printf ("%c", h[f].data);
       f=2*n-1;
  }    printf ("\ n"); int main () {    int flag=5,c     while (flag) {        & nbsp
printf ("Encoding and decoding of \n**************************** messages ********************\n");           printf ("\n**********1, Build Huffman    2, Code    3, decode  "
    0, exit system ****\n ");
          printf ("\n* hint: first set up Huffman tree, before encoding or decoding *\n");           printf ("\
n-------------------------------------------------------------------\ n ");
          scanf ("%d", &flag);           if (flag==1) {            
   node h[200];                code co[100];                int n;
Number of nodes                  n=create (h);
               scanf ("%d", &c);                while (c) {                 if (c==2) {          
         encoding (H,CO,N);                 }         & nbsp;         if (c==3) {            
        decoding (h,co,n);                 } &NBSP;&Nbsp;                if (c==0) {                      printf ("Exit system.")
\ n ");
                  break;                  }        &
nbsp;         scanf ("%d", &c);
              }                     Else if (flag==0) {                 printf ("Exit system.")
\ n ");
                break;          }           else{ &nBsp            printf ("Input error, please re-enter.")
\ n ");
         }    &nbsp}     return 0; }



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.