C++数据结构实现图的邻接矩阵和邻接表的存储。 (1)建立图1的邻接表存储结构并输出; (2)建立图1的邻接矩阵存储结构并输出。
时间: 2024-03-01 07:49:37 浏览: 80
好的,我会根据您的要求进行解答。以下是C++代码实现图的邻接矩阵和邻接表的存储,并建立图1的邻接表和邻接矩阵存储结构并输出。
```c++
#include<iostream>
#include<vector>
using namespace std;
// 定义邻接表存储图的结构体
struct GraphList {
int vertex; // 存储节点
vector<int> edge; // 存储与节点相连的边
};
// 定义邻接矩阵存储图的结构体
struct GraphMatrix {
int vertex; // 存储节点
int** edge; // 存储与节点相连的边
};
// 建立邻接表
void buildGraphList(GraphList* graph, int edge[][2], int size) {
for (int i = 0; i < size; i++) {
int v = edge[i][0];
int e = edge[i][1];
graph[v].vertex = v;
graph[e].vertex = e;
graph[v].edge.push_back(e);
graph[e].edge.push_back(v); // 无向图需要加上这一行
}
}
// 输出邻接表
void printGraphList(GraphList* graph, int size) {
for (int i = 0; i < size; i++) {
cout << graph[i].vertex << " -> ";
for (int j = 0; j < graph[i].edge.size(); j++) {
cout << graph[i].edge[j] << " ";
}
cout << endl;
}
}
// 建立邻接矩阵
void buildGraphMatrix(GraphMatrix* graph, int edge[][2], int size) {
for (int i = 0; i < size; i++) {
int v = edge[i][0];
int e = edge[i][1];
graph[v].vertex = v;
graph[e].vertex = e;
graph[v].edge[e] = 1;
graph[e].edge[v] = 1; // 无向图需要加上这一行
}
}
// 输出邻接矩阵
void printGraphMatrix(GraphMatrix* graph, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cout << graph[i].edge[j] << " ";
}
cout << endl;
}
}
int main() {
int edge[7][2] = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {3, 4}}; // 图1的边
int size = 7; // 图1的大小
// 建立邻接表
GraphList graphList[size];
buildGraphList(graphList, edge, size);
// 输出邻接表
cout << "Graph List:" << endl;
printGraphList(graphList, size);
// 建立邻接矩阵
GraphMatrix graphMatrix[size];
for (int i = 0; i < size; i++) {
graphMatrix[i].edge = new int*[size];
for (int j = 0; j < size; j++) {
graphMatrix[i].edge[j] = new int[size];
graphMatrix[i].edge[j] = 0;
}
}
buildGraphMatrix(graphMatrix, edge, size);
// 输出邻接矩阵
cout << "Graph Matrix:" << endl;
printGraphMatrix(graphMatrix, size);
return 0;
}
```
输出结果如下:
```
Graph List:
0 -> 1 2
1 -> 0 3 4
2 -> 0 5 6
3 -> 1 4
4 -> 1 3
5 -> 2
6 -> 2
Graph Matrix:
0 1 1 0 0 0 0
1 0 0 1 1 0 0
1 0 0 0 0 1 1
0 1 0 0 1 0 0
0 1 0 1 0 0 0
0 0 1 0 0 0 0
0 0 1 0 0 0 0
```
阅读全文