数据结构之邻接表存储图

用邻接表存图适合稀疏图,不会浪费太多空间。写的时候一定要思路清晰,点和边的结构体存储要明确他们都包含什么内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <bits/stdc++.h>
using namespace std;
typedef struct Arcnode{
int vertex,data; //这条边的终点 以及权值
struct Arcnode *nextArc; //与这条边同起点的下一条边
}Arcnode;
typedef struct vernode{
int data; //顶点数据
Arcnode *nextArc; // 以该点为起点的边
}vernode;
typedef struct {
vernode vertex[1001];
int vernum,arcnum;
}Graph;
int locate(Graph G, int x)
{
for(int i = 1 ; i <= G.vernum; ++i)
{
if(G.vertex[i].data == x)
{
return i;
}
}
}
void create(Graph &G)
{
int a,b,w;
cin >> G.vernum >> G.arcnum;
for(int i = 1; i <= G.vernum ; ++i)
{
cin >> G.vertex[i].data;
G.vertex[i].nextArc = NULL;
}
for(int i = 1; i <= G.arcnum; ++i)
{
cin >> a >> b >> w;
int A = locate(G,a);
int B = locate(G,b);
Arcnode *p,*p1;
p = new Arcnode; //!!!这一步总是忘记
p -> vertex = B;
p -> nextArc = G.vertex[A].nextArc;
p -> data = w;
G.vertex[A].nextArc = p;
p = new Arcnode;
p -> vertex = A;
p -> nextArc = G.vertex[B].nextArc;
p -> data = w;
G.vertex[B].nextArc = p;
}
}
int main()
{
Graph G;
create(G);
Arcnode *p;
for(int i = 1; i <= G.vernum; ++i){
p = G.vertex[i].nextArc;
while(p != NULL)
{
cout << p -> data << ' ' << p -> vertex << '\n';
p = p -> nextArc;
}
cout << '\n';
}
}