C语言编程建立频度链表来统计字符的频度
时间: 2024-03-13 22:17:55 浏览: 103
Huffman编码方法-数据结构c语言版严蔚敏
好的,我会尽力回答你关于C语言编程建立频度链表来统计字符频度的问题。首先,频度链表是一种数据结构,用于存储每个字符在给定文本中出现的次数。在C语言中,可以使用结构体和指针来实现频度链表。下面是一个示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHAR 128
typedef struct freq_node {
char character;
int frequency;
struct freq_node *next;
} FreqNode;
FreqNode *insert_node(FreqNode *head, char character) {
FreqNode *current = head;
while (current != NULL) {
if (current->character == character) {
current->frequency++;
return head;
}
current = current->next;
}
FreqNode *new_node = (FreqNode *)malloc(sizeof(FreqNode));
new_node->character = character;
new_node->frequency = 1;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
} else {
current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
return head;
}
void print_freq_list(FreqNode *head) {
FreqNode *current = head;
while (current != NULL) {
printf("%c:%d ", current->character, current->frequency);
current = current->next;
}
printf("\n");
}
int main() {
FreqNode *head = NULL;
char input[MAX_CHAR];
printf("请输入一行待统计字符频度的字符串:\n");
fgets(input, MAX_CHAR, stdin);
for (int i = 0; i < MAX_CHAR && input[i] != '\0' && input[i] != '\n'; i++) {
head = insert_node(head, input[i]);
}
printf("统计结果为:\n");
print_freq_list(head);
return 0;
}
```
以上是一个简单的实现,通过读入一行字符串后,使用 insert_node 函数将每个字符插入到频度链表中,如果链表中已存在该字符,则直接增加对应节点的 frequency 属性,否则创建新节点并插入到链表尾部。最后打印输出结果。希望这能解决你的问题,如果还有其他问题,欢迎继续咨询。
阅读全文