Huffman树

来源:互联网 发布:数据库 锁定客户群 编辑:程序博客网 时间:2024/05/20 01:35
#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\n",t->data);        inorder(t->lchild);        inorder(t->rchild);    }}int main(){    linkhuf t=creat();    creathuffman(&t);    inorder(t);}

0 0
原创粉丝点击