树的邻接表表示法

实现了书上这样的存储方式:

 

#ifndef listTree_H_
#define listTree_H_
#include 
#include 
#include 
#include 
#include 
using namespace std;

struct childNode
{
    int child;
    childNode *next;
};

struct headNode
{
    char data;
    int parent;
    childNode *firstChild;
};

class ListTree
{
public:
    ListTree();
    ~ListTree();
    void creat();
    void preOrder();
    void leverOrder();
private:
    headNode*node;
    int num;
};

ListTree::ListTree()
{
    node=NULL;
    cout<<"Please input the number of node in the tree."<>num;
}
//lever order to creat
void ListTree::creat()
{
    char temp[20];
    childNode *tempChild;
    node=new headNode[num];
    int i,j,k;
    cout<<"Input every data of the tree.(level order,first is root)"<>node[i].data;
        node[i].parent=-1;
        node[i].firstChild=NULL;
    }
    getchar();
    for(i=0; i=0; j--)
        {
            for(k=0; kchild=j;
                    tempChild->next=node[i].firstChild;
                    node[i].firstChild=tempChild;
                    node[j].parent=i;
                }
            }
        }
    }
}

void ListTree::leverOrder()
{
    int i;
    for(i=0; iS;
    cout<child])
            {
                cout<child].data<<" ";
                visited[cur->child]=1;
                S.push(cur->child);
                break;
            }
            cur=cur->next;
        }
        if(!cur)S.pop();
    }
}

ListTree::~ListTree()
{
    int i;
    childNode*temp;
    for(i=0; inext;
            delete(temp);
        }
        delete(&node[i]);
    }
}
#endif

测试:

#include 
#include "listTree.h"
using namespace std;

int main()
{
    ListTree test;
    test.creat();
    test.leverOrder();
    cout<

 

你可能感兴趣的:(数据结构C++实现)