用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

数据结构与算法----3.4 统计每个元素出现的次数

2019-07-21 作者: Ryan2019举报

[c++]代码库

#include <iostream>
using namespace std;
typedef int KeyType;
struct ElemType{KeyType key;int count;};
typedef struct BiTNode
{
    ElemType data;
    BiTNode *lc,*rc;
}*BiTree;
void BiTreeLists(BiTree T, void visit(ElemType));
BiTree CreatNode(ElemType x);
bool InsertBST(BiTree &T, ElemType x) ;
void visit(ElemType data);
void CreatBST(BiTree &T, int n, ElemType a[]);
void countall(BiTree &T);
int main()
{
    BiTree T; int n = 12,i;
    KeyType a[] = { 1,1,2,5,3,5,5,4,4,7,7,8 };
    ElemType b[12];
    for ( i = 0; i < n; i++) b[i].key =a[i];
    CreatBST(T, n,b);
    cout << "元素序列:" << endl;
    for ( i = 0; i < n; i++)
    {
        cout<<a[i] << " ";
    }
    cout << endl;
    countall(T);
    return 0;
}
BiTree CreatNode(ElemType x)
{
    BiTree p;
    p = new BiTNode; p->data = x;p->data.count = 1;
    p->lc = p->rc = NULL;
    return p;
}
void BiTreeLists(BiTree T, void visit(ElemType))
    if (!T) { cout << "#"; return; }
    visit(T->data);
    if (T->lc || T->rc) {
        cout << "(";
        BiTreeLists(T->lc, visit);
        cout << ",";
        BiTreeLists(T->rc, visit);
        cout << ")";
    }
}
void CreatBST(BiTree &T, int n, ElemType a[])
{
    T = NULL;
    for (int i = 0; i < n; i++) {
        InsertBST(T, a[i]);
    }
}
 
void visit(ElemType data)
{
    cout << data.key;
}
bool InsertBST(BiTree &T, ElemType x)
{
    if (!T)
    {
        T = CreatNode(x); return true;
    }
    else if (T->data.key == x.key)
    {
        T->data.count++;
        return false;
    }
    else if (x.key < T->data.key)
    {
        return InsertBST(T->lc, x);
    }
    else
    {
        return InsertBST(T->rc, x);
    }
}
void countall(BiTree &T)
{
    if (!T)return;
    countall(T->rc);
    cout << "元素" << T->data.key << "出现的次数:" << T->data.count << endl;
    countall(T->lc);
 
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...