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\n",t->data);
        inorder(t->lchild);
        inorder(t->rchild);
    }
}
int main()
{
    linkhuf t=creat();
    creathuffman(&t);
    inorder(t);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值