用数组模拟链表实现邻接表的妙用

图例

在这里插入图片描述

代码

#include<bits/stdc++.h>
using namespace std;
//Head 与 next 数组存储的是ver数组的下标,0表示指向空
//ver 数组存储的是每条边的终点
//使用数组实现邻接表,无向图
const int N = 1010;   //顶点数
const int M = 10100;  //边数
int head[N],Next[2*M],ver[2*M],dist[2*M],tot=-1;
void add(int x,int y,int z)
{
    ver[++tot] = y;    //这条边到达的点
    Next[tot] = head[x];  //链接
    head[x] = tot;    //标记x起点
    dist[tot] = z;  //权值
}
void printU(int u)
{
    //! 访问从u出发的所有边,当next[i]=0时遍历结束
    cout<<u<<":";
    for(int i=head[u];i;i=Next[i]){
        int v = ver[i];
        int d = dist[i];
        cout<<"("<<u<<","<<v<<","<<d<<")";
    }
}
int main()
{
    add(1,2,77);
    add(2,3,777);
    add(2,5,77777);
    add(3,5,77777);
    add(5,4,7777);
    add(5,1,7);
    for(int u=1;u<=5;u++){
        printU(u);
        cout<<endl;
    }
    return 0;
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章