数据结构——树的孩子表示法

#include <iostream>
using namespace std;

#define MAX_TREE_SIZE 100
typedef struct Cnode        //孩子节点
{
    char        child;
    struct    Cnode * next;
}* CNode;
typedef struct     
{
    char        data;
    int            parent;        //双亲位置域
    CNode    firstchild;    //孩子链表头指针
}PTNode;
typedef struct        //树结构
{
    PTNode node[MAX_TREE_SIZE];
    int count;        //节点个数
}CTree;

//初始化树
void init_ptree(CTree &tree)
{
    tree.count=-1;
    int i;
    for(i=0;i<MAX_TREE_SIZE;i++)
        tree.node[i].firstchild=NULL;
}
//添加节点
void add_ptnode(CTree &tree, PTNode ptnode)
{
    tree.count++;
    tree.node[tree.count].data = ptnode.data;
    tree.node[tree.count].parent = ptnode.parent;
    
    CNode temp=(CNode)malloc(sizeof(CNode));
    temp->child=ptnode.data;
    temp->next=NULL;

    if(ptnode.parent>=0)
    {
        if(NULL == tree.node[ptnode.parent].firstchild)        //尚未接孩子
        {
            tree.node[ptnode.parent].firstchild = temp;
        }
        else
        {
            CNode pre=tree.node[ptnode.parent].firstchild;    
            while(NULL != pre->next)    
                pre=pre->next;
            pre->next=temp;
        }
    }
}

//输出树
void print_ctree(CTree &tree)
{
    int i;
    for(i=0;i<=tree.count;i++)
    {
        cout<<"    "<<i<<"        "<<tree.node[i].data<<"        "<<tree.node[i].parent<<"      ";
        CNode temp=tree.node[i].firstchild;
        while(temp!=NULL)
        {
            cout<<temp->child<<"   ";
            temp=temp->next;
        }
        cout<<endl;
    }
}

int main()
{
    FILE *fin=fopen("树的表示法.txt","r");

    CTree ctree;
    init_ptree(ctree);
    PTNode ptnode;

    while(fscanf(fin,"%c%d",&ptnode.data,&ptnode.parent)!=EOF)
    {
        add_ptnode(ctree,ptnode);
        fscanf(fin,"%c%d",&ptnode.data,&ptnode.parent);
    }
    //输出树
    cout<<"数组下标  节点值  双亲位置   子节点"<<endl;
    print_ctree(ctree);

    fclose(fin);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

minyuanxiani

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值