统计一个字符串中出现的字符及其次数

/**
*    实验题目:
*        统计一个字符串中出现的字符及其次数
*    实验目的:
*        掌握二叉排序树的构造过程及其算法设计
*    实验内容:
*        设计程序,读入一个字符串,统计该字符串中每个出现的字符及其
*    次数,然后按字符的ASCII编码顺序输出结果。
*    要求用一颗二叉排序树来保存处理结果,每个结点包含四个域,格式为:
*    字符
*    该字符出现的次数
*    指向ASCII码值小于该字符的左子树指针
*    指向ASCII码值大于该字符的右子树指针
*/

#include <stdio.h>
#include <string.h>
#include <malloc.h>


#define MAX_WORD (100)

typedef struct tnode
{
    char ch;                                //  字符
    int cnt;                                //  出现次数
    struct tnode *lchild;                   //  左指针
    struct tnode *rchild;                   //  右指针
}BSTNode;                                   //  结点类型

/*-----------------采用递归方式向二叉排序树bst中插入一个字符----------------*/
static void create_bst(BSTNode *&bt, char ch)               // 指针的引用
{
    if(bt == NULL)                                          // bt为空,则建立一个新结点
    {
        bt = (BSTNode *)malloc(sizeof(BSTNode));
        bt->ch = ch;
        bt->cnt = 1;
        bt->lchild = bt->rchild = NULL;
    }
    else if(ch == bt->ch)
        bt->cnt++;
    else if(ch < bt->ch)
        create_bst(bt->lchild, ch);
    else
        create_bst(bt->rchild, ch);
}

/*-----------------中序遍历二叉排序树bst----------------*/
static void inorder(BSTNode *bt)
{
    if(bt != NULL)
    {
        inorder(bt->lchild);                    //  中序遍历左子树
        printf("  %c(%d)\n", bt->ch, bt->cnt); //  访问根结点
        inorder(bt->rchild);                    //  中序遍历右子树
    }
}

/*-----------------销毁二叉排序树bst----------------*/
static void destroy_bst(BSTNode *bt)
{
    if(bt != NULL)
    {
        destroy_bst(bt->lchild);
        destroy_bst(bt->rchild);
        free(bt);
    }
}

int main(int argc, char *argv[])
{
    BSTNode *bt = NULL;
    int i = 0;
    char str[MAX_WORD];

    printf("输入字符串:");
    gets(str);
    while(str[i] != '\0')
    {
        create_bst(bt, str[i]);
        i++;
    }
    printf("字符及出现次数:\n");
    inorder(bt);
    printf("\n");
    destroy_bst(bt);

    return 0;
}
测试结果:

输入字符串:Good Bye!
字符及出现次数:
   (1)
  !(1)
  B(1)
  G(1)
  d(1)
  e(1)
  o(2)
  y(1)

  • 11
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值