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){

//待补全,读入字符串,以'$'为结束符,根据每个字符出现频率为权值,构造森林。

}

cpp 复制代码
#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;
	}

}
相关推荐
没有梦想的咸鱼185-1037-166324 分钟前
基于R语言机器学习方法在生态经济学领域中的实践技术应用
开发语言·机器学习·数据分析·r语言
向上的车轮1 小时前
基于go语言的云原生TodoList Demo 项目,验证云原生核心特性
开发语言·云原生·golang
The Chosen One9851 小时前
C++ : AVL树-详解
开发语言·c++
zzyzxb1 小时前
std::enable_shared_from_this
c++
SNAKEpc121381 小时前
QML和Qt Quick
c++·qt
PH_modest1 小时前
【Qt跬步积累】—— 初识Qt
开发语言·qt
hansang_IR1 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
GanGuaGua1 小时前
Linux系统:线程的互斥和安全
linux·运维·服务器·c语言·c++·安全
怀旧,1 小时前
【C++】18. 红⿊树实现
开发语言·c++
lsnm1 小时前
【LINUX网络】IP——网络层
linux·服务器·网络·c++·网络协议·tcp/ip