#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 1024
typedef struct{
char data;
int weight;
int parent;
int lchild;
int rchild;
}Huffnode,*Hufftree;
typedef struct stack{
int top;
int elem[MAX_SIZE];
}Stack;
void Initstack(Stack *s)
{
s->top=-1;
}
void push(Stack *s,int e)
{
s->top++;
s->elem[s->top]=e;
}
int pop(Stack *s)
{
return s->elem[s->top--];
}
bool isempty(Stack *s)
{
if(s->top==-1)
return true;
else
return false;
}
void GetHuffmamCode(Hufftree a,int n)
{
int i,j,s1,s2,max,c,p;
Stack s;
char ch;
Initstack(&s);
printf("輸入字符集:");
for(i=1;i<=n;i++)
{
scanf("%c",&a[i].data);
scanf("%c",&ch);
}
printf("輸入權值:");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i].weight);
scanf("%c",&ch);
}
int m=2*n-1;
for(i=1;i<=n;i++)
{
a[i].parent=0;
a[i].rchild=0;
a[i].lchild=0;
}
for(i=n+1;i<=m;i++)
{
a[i].data=https://bbs.csdn.net/topics/NULL;
a[i].weight=0;
a[i].parent=0;
a[i].lchild=0;
a[i].rchild=0;
}
for(i=n+1;i<=m;i++)
{
max=65535;
for(j=1;j<=i-1;j++)
{
if(a[j].parent==0&&a[j].weight<=max)
{
s1=j;
max=a[j].weight;
}
}
a[s1].parent=i;
max=65535;
for(j=1;j<=i-1;j++)
{
if(a[j].parent==0&&a[j].weight<=max)
{
s2=j;
max=a[j].weight;
}
}
a[s2].parent=i;
a[i].weight=a[s1].weight+a[s2].weight;
a[i].lchild=s1;
a[i].rchild=s2;
}
for(i=1;i<=n;i++)
{
c=i;
p=a[i].parent;
while(p!=0)
{
if(a[p].lchild==c)
push(&s,0);
else
push(&s,1);
c=p;
p=a[p].parent;
}
printf("%c\n",a[i].data);
while(!isempty(&s))
printf("%d",pop(&s));
printf("\n");
}
}
int main()
{
Hufftree a;
int n;
int m;
printf("輸入字符個數:");
scanf("%d",&n);
m=2*n-1;
a=(Hufftree)malloc(sizeof(Huffnode)*m);
GetHuffmamCode(a,n);
return 0;
}
uj5u.com熱心網友回復:
太長沒太仔細看你的a,陣列下標應該從0到m-1,但你的處理卻是從1到m,造成記憶體越界了吧?
uj5u.com熱心網友回復:
printf("%c\n",a[i].data);前面隨便列印輸出一行字串,看看程式走到這個輸出陳述句了嗎轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/249952.html
標籤:C語言
上一篇:求大佬,不會寫了
