zoukankan      html  css  js  c++  java
  • Huffman树

    #include<stdio.h>
    #include<stdlib.h>
    #include<malloc.h>
    typedef struct node
    {
        int data;
        struct node *lchild,*rchild,*next;
    }hufnode;
    typedef hufnode *linkhuf;
    linkhuf insert(linkhuf root,linkhuf s)
    {
        linkhuf p1,p2;//p1查找位置的前驱,p2查找插入位置
        if(root==NULL)root=s;//空树
        else
        {
            p1=NULL;
            p2=root;
            while(p2&&p2->data<s->data)
            {
                p1=p2;
                p2=p2->next;
            }
            s->next=p2;
            if(p1==NULL)root=s;
            else p1->next=s;
        }
        return root;
    }
    //创建哈夫曼树
    void creathuffman(linkhuf *root)
    {
        linkhuf s,r1,rr;
        while(*root&&(*root)->next)
        {//每次从链表上摘下两个节点作为新生成的左右子树
            r1=*root;
            rr=(*root)->next;
            *root=rr->next;
            s=(linkhuf)malloc(sizeof(hufnode));
            s->next=NULL;
            s->data=r1->data+rr->data;
            s->lchild=r1;
            s->rchild=rr;
            r1->next=rr->next=NULL;
            *root=insert(*root,s);
        }
    }
    //创建链表
    linkhuf creat()
    {
        int x;
        linkhuf t=NULL,p,pre;
        scanf("%d",&x);
        if(x>0){
            p=t=(hufnode*)malloc(sizeof(hufnode));
            p->data=x;
            t->next=t->lchild=t->rchild=NULL;
        }
        while(scanf("%d",&x)!=EOF,x>0)
        {
            pre=(hufnode*)malloc(sizeof(hufnode));
            pre->next=pre->lchild=pre->rchild=NULL;
            pre->data=x;
            p->next=pre;
            p=pre;
        }
        return t;
    }
    void inorder(linkhuf t)
    {
        if(t)
        {
            printf("%d
    ",t->data);
            inorder(t->lchild);
            inorder(t->rchild);
        }
    }
    int main()
    {
        linkhuf t=creat();
        creathuffman(&t);
        inorder(t);
    }
    

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    python之----------字符编码具体原理
    python ---------函数
    python爬虫
    python str 与repr区别
    python 正则表达式
    python 正则表达式里使用 split()方法
    python 基础介绍
    python 数据类型--列表
    python 字符串操作
    django(1.6)操作自带的数据库
  • 原文地址:https://www.cnblogs.com/Thereisnospon/p/4768503.html
Copyright © 2011-2022 走看看