C++ 统计一个字符串当每个字符出现的权重。

编程入门 行业动态 更新时间:2024-10-28 04:21:00

C++ 统计一个字符串当每个字符出现的<a href=https://www.elefans.com/category/jswz/34/1758801.html style=权重。"/>

C++ 统计一个字符串当每个字符出现的权重。

abbccc$b

b:2

本题目为第一步,读入待编码字符串,建造一个森林,请补全下列代码。


#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef char elemtype;


//带权值的二叉树

typedef struct BiTNode{
elemtype data;
int weight; //权重
struct BiTNode *lchild, *rchild; /*左右孩子指针*/
}BiTNode,*BiTree;

//用单链表表示森林

typedef struct linkNode{
BiTree tree;
struct linkNode *next;
}LinkNode, *Forest;
//创建森林

int createForest(Forest forest){
//待补全,读入字符串,以‘$'为结束符,根据每个字符出现频率为权值,构造森林。并返回森林中树的个数

}


int main()
{Forest forest = malloc(sizeof(linkNode));
//森林的单链表包含一个头结点,头结点符号‘$'

forest->tree = malloc(sizeof(BiTNode));
forest->tree->data = '$';
forest->next = NULL;createForest(forest);

char ch1;
scanf("%c", &ch1);
linkNode * p = forest->next;
while (p != NULL)
{
if (p->tree->data == ch1)
{
printf("%c:%d\n", p->tree->data, p->tree->weight);
}
p = p->next;
}

}


输入
abbccc$b
输出
b:2


样例输入 Copy
hello world$l
样例输出 Copy
l:3
提示
只需要补全并提交以下代码:


//创建森林

int createForest(Forest forest){
//待补全,读入字符串,以‘$'为结束符,根据每个字符出现频率为权值,构造森林。

}

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>typedef char elemtype;//带权值的二叉树
typedef struct BiTNode {elemtype data;int weight; //权重struct BiTNode* lchild, * rchild; /*左右孩子指针*/
}BiTNode, * BiTree;//用单链表表示森林
typedef struct linkNode {BiTree tree;struct linkNode* next;
}LinkNode, * Forest;//创建森林
int createForest(Forest forest)
{//待补全,读入字符串,以‘$'为结束符,根据每个字符出现频率为权值,构造森林。并返回森林中树的个数int count = 0; // 森林中树的个数BiTree tree;LinkNode* p = forest;char ch;char list[128] = {0};scanf("%c", &ch);while (ch != '$') {scanf("%c", &ch);list[ch] += 1;}for (int i = 0; i < 128; i++) {if (!list[i])continue;tree = (BiTNode*)malloc(sizeof(BiTNode));tree->data = i;tree->weight = list[i];tree->lchild = NULL;tree->rchild = NULL;LinkNode* newNode = (LinkNode*)malloc(sizeof(LinkNode));newNode->tree = tree;newNode->next = NULL;p->next = newNode;p = p->next;count++;}return count;
}int main()
{Forest forest = (linkNode*)malloc(sizeof(linkNode));//森林的单链表包含一个头结点,头结点符号‘$'forest->tree = (BiTNode*)malloc(sizeof(BiTNode));forest->tree->data = '$';forest->next = NULL;createForest(forest);char ch1;scanf("%c", &ch1);linkNode* p = forest->next;while (p != NULL){if (p->tree->data == ch1){printf("%c:%d\n", p->tree->data, p->tree->weight);}p = p->next;}}

更多推荐

C++ 统计一个字符串当每个字符出现的权重。

本文发布于:2023-11-16 12:19:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:权重   字符串   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!