【发布时间】:2021-08-12 02:22:37
【问题描述】:
基本上,对于我的任务,我需要实现代码来进行霍夫曼编码。为此,我需要将输入作为字符串,然后创建一个字符列表及其频率。当有新角色时,我需要创建一个新节点。我曾尝试在 C 中这样做,但没有结果。当我尝试打印我的链接列表时,我根本无法获得任何输出。我相信我从一开始就未能创建列表。 我的 C 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct node {
char character;
int frequency;
struct node *next;
}head;
struct node *insert(int frequency, char character) {
struct node *newNode = malloc(sizeof(struct node));
newNode->character = frequency;
newNode->character = character;
return newNode;
}
void create_freq_list(struct node *initial, int str_size, char str[]) {
int i;
struct node *temp;
bool has_node;
for (i = 0; i < str_size; i++) {
temp = initial;
has_node = false;
while (temp->next != NULL) {
if (temp->character == str[i]) {
has_node = true;
temp->frequency++;
}
temp = temp->next;
}
if (has_node == false) {
while (temp->next != NULL) {
temp = temp->next;
if (temp->next == NULL) {
temp->next = insert(0, str[i]);
}
}
}
}
}
int main() {
struct node *temp;
char str[100];
gets_s(str, 100);
create_freq_list(&head, 100, str);
temp = &head;
while (temp->next != NULL) {
printf("'%c' : %d", temp->character, temp->frequency);
temp = temp->next;
}
getch();
exit(0);
}
【问题讨论】:
-
必须是链表吗?对于已知元素数量的频率计数器,数组效果很好。
-
你可以使用什么调试器?
-
另外,如果你可以使用 C++,你瞧,somebody already did that。但是是的,John 可能是对的,字符只有这么多,这就是为什么以 char 为索引的数组效果很好的原因。
-
除了将
character分配给frequency之外,您的代码中的主要问题是您从未在insert中将next设置为null(这也是错误的命名)。 -
@dekaottoman:您可以通过点击分数下方的灰色复选标记来接受答案。
标签: c linked-list huffman-code