邻接表用数组来实现的思路

https://blog.csdn.net/nyist_yangguang/article/details/113468345

邻接表用链表实现其实也很简单,但是程序比较长。

如果换一种考虑思路,使用数组来实现邻接表,这种方法很容易理解,很直观,操作起来也简单一些。

测试程序

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int u[100],v[100],w[100];
int first[100],next[100];
int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d %d %d",&u[i],&v[i],&w[i]);
        first[i]=-1;
        next[i]=-1;
    }
    for(int i=1; i<=m; i++)
    {
        if(first[u[i]]==-1)
            first[u[i]]=i;
        else
        {
            next[i]=first[u[i]];
            first[u[i]]=i;
        }
    }

    int temp;

    for(int i=1; i<=m; i++)
    {
        temp=first[i];
        while(temp!=-1)
        {
            cout<<u[temp]<<"  "<<v[temp]<<"  "<<w[temp]<<endl;
            temp=next[temp];
        }
    }


}

测试结果

猜你喜欢

转载自blog.csdn.net/nyist_yangguang/article/details/113441111