用户注册



邮箱:

密码:

用户登录


邮箱:

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

发表随想


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

数据结构与算法----2.8 实现森林的层序遍历算法

2019-07-21 作者: Ryan2019举报

[c++]代码库

#include <iostream>
using namespace std;
typedef char TElemType;
typedef struct TNode
{
    TElemType data;
    TNode*parent,*fc,*ns;
}FNode,*tree,*forest;
typedef forest QElemType;
typedef struct QNode
{
    QElemType data; QNode *next;
}*LQueuePtr;
struct LQueue{ LQueuePtr front,rear;};
void QueueInit(LQueue &Q);//队初始化
void Enqueue(LQueue &Q,QElemType e);//入队
bool Dequeue(LQueue &Q,QElemType &e);//出队
void ForestLists(tree T);
void TreeLists(tree T);
void CreateForest(forest &T, char s[], int &i);
void CreateForest(forest &T, char s[]);
void ForestLevelOrder(forest F, void visit(TElemType));//森林的层序遍历输出
void visit(TElemType data);
int main()
{
    forest F;
    char s[]="BC#D##F##";
    CreateForest(F,s);
    cout<<"该森林为:"<<endl;
    ForestLists(F);
    cout<<endl<<"该森林的层序遍历输出为:";
    ForestLevelOrder( F,visit);
    cout<<endl;
    return 0;
}
void QueueInit(LQueue &Q)
{
    Q.front=new QNode;
    Q.front->next=NULL;
    Q.rear=Q.front;
}
void Enqueue(LQueue &Q,QElemType e)
{
    LQueuePtr p;
    p=new QNode;p->data=e;p->next=NULL;
    Q.rear->next=p;Q.rear=p;
}
bool Dequeue(LQueue &Q,QElemType &e)
{
    LQueuePtr p;
    if(Q.front==Q.rear) return false;
    p=Q.front;Q.front=p->next;e=Q.front->data;
    delete p;return true;  
}
void CreateForest(forest &T, char s[], int &i)
    i++;
    if (s[i] == '#') { T = NULL; return; }
    T = new TNode;
    T->data = s[i];      //建立根节点
    CreateForest(T->fc, s, i);
    CreateForest(T->ns, s, i);
}
void CreateForest(forest &T, char s[])
    int i = -1;
    CreateForest(T, s, i);
}
void TreeLists(tree T)
{
    tree p;
    if (!T) { cout << "#"; return; }
    cout<<T->data;
    p = T->fc;   
    if (!p)return;
    cout << "(";
    while(p){
        TreeLists(p);
        p = p->ns;
        if (p)cout << ",";
    }
    cout << ")";
}
void ForestLists(tree T)
{                   
    forest p = T;
    cout << "(";
    while (p) {
        TreeLists(p);
        p = p->ns;
        if (p)cout << ",";
    }
    cout << ")";
}
void visit(TElemType data)
 {
    cout << data;
}
void ForestLevelOrder(forest F, void visit(TElemType))
{
    LQueue q;forest x,y;
    if(!F)return ;
    QueueInit(q);
    for (F; F; F = F->ns)
    {
        Enqueue(q,F);
    }
    while(Dequeue(q,x))
    {
        visit(x->data);
        for(y=x->fc;y;y=y->ns)        Enqueue(q,y);
    }
}


网友评论    (发表评论)


发表评论:

评论须知:

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


扫码下载

加载中,请稍后...

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

加载中,请稍后...