链式前向星
用边作为储存核心
struct Edge
{
int to; //边的尾点
int w; //边权值
int next; //指向上一条边
} edge[maxn];
int head[maxn];
问题一:边的另一个节点在哪?
与邻接矩阵储存逻辑很像,有一个“头”,用head[]里的下标表示。
问题二:怎么去模拟邻接矩阵的头后接一个一个的节点?
void addEdge(int from, int to, int w)
{
edge[cnt].to = to; //边的尾点`
edge[cnt].w = w; //边权`
edge[cnt].next = head[from]; //指向上一条边`
head[from] = cnt++; //注意先赋值再加一,head[from] = cnt, 那么下一个以from作为始点的边的next将会是现 在这条边`
}
问题三:怎么遍历?
memset(head, -1, sizeof(head));
//遍历所有顶点
for(int i = 1; i <= v; i++)
{
//j != -1 可以这样写 ~j
//查找与顶点相关联的边
for(int j = head[i]; ~j; j = edge[j].next)
{
cout << i << " "<< edge[j].to << " " << edge[j].w;
cout << endl;
}
}
四、完整代码
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
const int maxn = 1005;
struct Edge
{
int to; //边的尾点
int w; //边权值
int next; //指向上一条边
} edge[maxn];
int v, e, cnt, head[maxn];
void inti()
{
//表示指向为空
memset(head, -1, sizeof(head));
}
void addEdge(int from, int to, int w)
{
edge[cnt].to = to;
edge[cnt].w = w;
edge[cnt].next = head[from];
head[from] = cnt++;
}
int main()
{
inti();
ifstream in("graph.txt", ios::in);
in >> v >> e;
int from, to, w;
for(int i = 0; i < e; i++)
{
in >> from >> to >> w;
addEdge(from, to, w);
}
for(int i = 1; i <= v; i++)
{
for(int j = head[i]; ~j; j = edge[j].next)
{
cout << i << " "<< edge[j].to << " " << edge[j].w;
cout << endl;
}
}
return 0;
}
输出情况: