C++代码如下:
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 100 + 5;
int head[maxn];
//n表示结点数,m表示边数,cnt表示边的下标计数
int n, m, x, y, w, cnt;
struct Edge{
int to, w, next;
}e[maxn * maxn];
//创建无向网的链式前向星
void init() {
memset(head, -1, sizeof(head));
cnt = 0;
}
//添加一条边u--v
void add(int u, int v, int w) {
e[cnt].to = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt++;
}
//输出链式前向星
void printg() {
cout << "----------链式前向星如下:----------" << endl;
for(int v = 1; v <= n; v++) {
cout << v << ":";
for(int i = head[v]; ~i; i = e[i].next) {
int v1 = e[i].to, w1 = e[i].w;
cout << "[" << v1 << " " << w1 << "] ";
}
cout << endl;
}
}
int main() {
cin >> n >> m;
init();
for(int i = 1; i <= m; i++) {
cin >> x >> y >> w;
add(x, y, w);
add(y, x, w);
}
printg();
}
样例运行结果如下: