【发布时间】:2015-12-07 15:06:13
【问题描述】:
目的是读取文件,计算每个字符的频率并执行霍夫曼编码,其中最常见的字母将是短二进制代码,即 001,而最不常见的字母会更长,即 01000100。
我创建了一个链接列表,其中包含所有字符及其各自频率的排序(按升序)列表。这被传递给下面的函数。在这个函数中,我的目标是添加两个最低频率并像这样构建二叉树,直到树的长度为 1。我不确定从这里去哪里,我知道我必须查看树并查看哪个将它向左或向右移动,然后存储 0(左)或 1(右)。 - 但我不知道如何构建一个函数来做到这一点!
void traverse_list(pqueue *list)
{
char letters[CHARACTERS] = { 0 };
int frequencies[CHARACTERS] = { 0 };
int j = 0, l = 0, len = 0;
node *temp = list->head;
tree *array[CHARACTERS];
while (temp != NULL)
{
letters[j] = temp->letter;
frequencies[j] = temp -> frequency;
temp = temp->next;
j++;
}
for (l = 0; l < CHARACTERS; l++)
{
if (frequencies[j])
{
tree* huffman = calloc(1, sizeof(tree));
huffman -> letter = letters[l];
huffman -> frequency = frequencies[l];
array[len++] = huffman;
}
}
while (len > 1)
{
tree* huffman = malloc(sizeof(tree));
huffman -> left = array[len--];
huffman -> right = array[len--];
huffman -> frequency = huffman -> left -> frequency + huffman -> right -> frequency;
array[len++] = huffman;
}
}
为了便于阅读,结构如下所示:
typedef struct Node
{
char letter;
int frequency;
struct Node *next;
}node;
typedef struct pqueue
{
node *head;
}pqueue;
typedef struct tree
{
struct tree *left;
struct tree *right;
char letter;
int frequency;
}tree;
【问题讨论】:
-
我现在改一下。
标签: c linked-list binary-tree huffman-code