1. 程式人生 > >資料結構之樹的孩子連結串列表示法

資料結構之樹的孩子連結串列表示法

#include"tree.h"
const int max = 100;
typedef char TElemType;
typedef struct CTNode
{
    int child;
    struct CTNode *next;
}*ChildPtr,CTNode;
typedef struct
{
    int parent;
    TElemType data;
    ChildPtr firstchild;
}CTBox;
typedef  struct
{
    CTBox node[max];
    int n, r;
}CTree;

void CreateTree(CTree &tree)
{
    ChildPtr childhead = NULL, childltemp = NULL, childs=NULL;
    int count,num;
    cout << "請輸入樹的結點個數" << endl;
    cin >> tree.n;
    for (int i = 0; i < tree.n; i++)
    {
        cout << "請輸入第:" << i<<"個結點的值" << endl;
        cin >> tree.node[i].data;
        cout << "請輸入它的雙親的序號" << endl;
        cin >> tree.node[i].parent;
        cout << "請輸入它孩子的個數" << endl;
        cin >> count;
        if (0 == count)
            tree.node[i].firstchild = NULL;
        else
        {
                childhead = (ChildPtr)malloc(sizeof(CTNode));
                cout << "輸入第一個孩子的序號" << endl;
                cin >> num;
                childhead->child = num;
                childhead->next = NULL;
                count--;
                childltemp = childhead;
                while (count > 0)
                {
                    childs= (ChildPtr)malloc(sizeof(CTNode));
                    cout << "請輸入下一個孩子的序號" << endl;
                    cin >> num;
                    childs->child = num;
                    childs->next = NULL;
                    childltemp->next = childs;
                    childltemp = childs;
                    count--;
                }
                tree.node[i].firstchild = childhead;
        
        }


    }
}

void Print(CTree tree)
{
    ChildPtr temp = NULL;
    for (int i = 0; i < tree.n; i++)
    {
        cout << "第" << i << "個結點的值:" << tree.node[i].data << endl;
        cout << "它的孩子的值為:" << endl;
        temp = tree.node[i].firstchild;
        if (temp != NULL)
        {
            while (temp != NULL)
            {
                cout << tree.node[temp->child].data << "  ";
                temp = temp->next;
            }
            cout << endl;

        }
        else
            cout << "該節點無孩子" << endl;
    }
}

int main()
{
    CTree tree;
    CreateTree(tree);
    Print(tree);
    return 0;
}