【发布时间】:2014-05-22 02:10:56
【问题描述】:
我必须解压缩一个用 Huffman 树编码的字符串,但代码长度可变,并且并非所有输入都在前缀中,在这种情况下,我应该打印“无效”并完成执行。输入包括:不同字符的数量;字符及其代码;编码消息的长度;编码消息。
如果可以的话,我会问一个更具体的问题,但我真的不知道出了什么问题,因为我觉得一切都错了。
示例输入将是: 6 11 米101 × 100 l 011 第 010 页 00 18 111001110101001100
它的输出是: “示范”
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node_t
{
struct node_t *left, *right;
char* codigo;
unsigned char c;
} *node;
void decode(const char *s, node t)
{
node q = t;
while (*s)
{
if (*s++ == '0') q = q->left;
else q = q->right;
if (q->c) putchar(q->c), q = t;
}
putchar('\n');
}
struct node_t *insere(struct node_t *root, char x, char* h, int a)
{
if(!root)
{
root=(struct node_t*)malloc(sizeof(struct node_t));
root->c = x;
root->codigo=h;
root->left = NULL;
root->right = NULL;
return(root);
}
else
{
if(h[a]=='0')
{
if(root->left!=NULL)
{
printf("invalid\n");
exit(0);
}
root->left = insere(root->left,x, h, a+1);
}
else
{
if(h[a]=='1')
{
if(root->left!=NULL)
{
printf("invalid\n");
exit(0);
}
root->right = insere(root->right,x, h, a+1);
}
}
}
return(root);
}
void inorder(struct node_t *root)
{
if(root != NULL)
{
inorder(root->left);
free(root);
inorder(root->right);
}
return;
}
int main(void)
{
struct node_t *root;
root = NULL;
int i, N, M, k;
scanf("%d", &N);
char item, num[2*N];
for (i = 0; i < N; i++)
{
scanf("%c %s\n", &item, num);
root= insere(root, item, num, 0);
}
scanf("%d\n", &M);
char buf[M];
for (k=0; k<M; k++)
scanf ("%c", &buf[k]);
decode (buf, root);
inorder(root);
return 0;
}
【问题讨论】:
-
错误是什么?分段故障?解析错误?输出错误?
标签: c tree decoding prefix huffman-code