邻接矩阵变成邻接表

本文介绍了一个使用C++实现的简单树类,该类可以创建邻接矩阵并将其转换为邻接表形式。文章展示了如何输入顶点数量和边的数量,然后通过输入具体的边来构建邻接矩阵。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string.h>
#include <stdlib.h>


using namespace std;


const int MaxSize = 100;


struct ArcNode
{
    int adjvex;
    ArcNode *next;
};


struct VertexNode
{
    int vertex;
    ArcNode *firstedge;
} ;


class Tree
{
private:
    int vertex[MaxSize];
    int arc[MaxSize][MaxSize];
    int vertexNum, arcNum,index;
    VertexNode root[MaxSize];
public:
    Tree()
    {
        vertexNum = arcNum = 0;
        index=0;
    }
    void push(int n, int e)
    {
        vertexNum = n;
        arcNum = e;
        for(int i = 0; i < n ; i++)
        {
            for(int j = 0; j < n ; j++)
            {
                arc[i][j] = 0;
            }
        }
        int i,j;
        while(index < e)
        {
            cin >> i >> j;
            index++;
            arc[i][j] = arc[j][i] = 1;
        }
    }
    ~Tree() {}
    void bulid()
    {
        for(int i=0;i<vertexNum;i++)
        {
            root[i].vertex=i;
            root[i].firstedge=NULL;
            for(int j=0;j<vertexNum;j++)
            {
                if(arc[i][j]==1)
                {
                    ArcNode *s=new ArcNode();
                    s->adjvex=j;
                    s->next=root[i].firstedge;
                    root[i].firstedge=s;
                }
            }
        }
    }
    void pop()
    {
        for(int i=0;i<vertexNum;i++)
        {
            cout<<root[i].vertex<<":";
            ArcNode *s;
            s=root[i].firstedge;
            while(s!=NULL)
            {
                int j;
                j=s->adjvex;
                cout<<j<<" ";
                s=s->next;
            }
            cout<<endl;
        }
    }
    void print()
    {
        for(int i = 0; i < vertexNum; i++)
        {
            for(int j = 0; j < vertexNum; j++)
            {
                cout<<arc[i][j]<<" ";
            }
            cout<<endl;
        }
    }
};


int main()
{
    Tree p;
    p.push(4, 4);
    cout<<"邻接矩阵为:"<<endl;
    p.print();
    p.bulid();
    cout<<"邻接表为:"<<endl;
    p.pop();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值