三种存图方式(邻接矩阵,邻接表,链式前向星)

#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include <iostream>
using namespace std;
const int MAXN=10;
struct node
{
    int to,cost;
};
int a[MAXN][MAXN];
vector<node> v[MAXN];
int n,m=5;  //m个顶点
void init1()  //邻接矩阵
{
    int i,j;
    for(i=1;i<=n;i++)
    {
        int x,y,z=1;  //z为权值,也可自己输入
        cin>>x>>y;
        a[x][y]=z;
    }
    for(i=1;i<=m;i++)
    {
        for(j=1;j<=m;j++)
           cout<<a[i][j]<<" ";
        cout<<endl;
    }
    return ;
}
void init2()   //邻接表
{
    int i,j;
    for(i=1;i<=n;i++)
    {
        int x;
        node y;
        y.cost=1;   //cost为权值
        cin>>x>>y.to;
        v[x].push_back(y);
    }
    for(i=1;i<=m;i++)
    {
        for(j=0;j<v[i].size();j++)
            cout<<i<<" "<<v[i][j].to<<" "<<v[i][j].cost<<endl;
    }
    return ;
}
int cnt=0;
int head[MAXN];
struct Node
{
    int to,cost,next;
}edge[MAXN];
void init3()   //链式前向星
{
    int i,j;
    int start,endd,cost;
    memset(head,-1,sizeof(head));
    for(i=0;i<n;i++)
    {
        cost=1;
        scanf("%d%d",&start,&endd);
        edge[cnt].to=endd;
        edge[cnt].cost=cost;
        edge[cnt].next=head[start];
        head[start]=cnt++;
    }
    for(start=1;start<=m;start++)
        for(i=head[start];i!=-1;i=edge[i].next)
            printf("(%d %d)--> %d
",start,edge[i].to,edge[i].cost);
    return ;
}
int main()
{
    cin>>n;   //输入n组数据
    init1();  //邻接矩阵
    init2();  //邻接表
    init3();  //链式前向星
    return 0;
}




样例:
7
1 2
2 3
3 4
1 3
4 1
1 5
4 5
邻接矩阵运行结果
0 1 1 0 1
0 0 1 0 0
0 0 0 1 0
1 0 0 0 1
0 0 0 0 0
邻接表运行结果
1 2 1
1 3 1
1 5 1
2 3 1
3 4 1
4 1 1
4 5 1
链式前向星运行结果
(1 5)-->1
(1 3)-->1
(1 2)-->1
(2 3)-->1
(3 4)-->1
(4 5)-->1
(4 1)-->1
原文地址:https://www.cnblogs.com/jk17211764/p/9677348.html