使用C++编写一个程序,设计带权图的邻接矩阵与邻接表的创建和输出运算,并在此基础上设计一个主程序完成以下功能:1)建立如图1所示的有向图G的邻接矩阵,并输出;2)建立如图1所示的有向图G的邻接表,并输出;3)销毁图G的邻接表。
时间: 2023-12-03 10:44:18 浏览: 76
这是一个关于图的基本操作的C++程序,包括邻接矩阵和邻接表的创建、输出和销毁。
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义图的最大顶点数
const int MAX_VERTEX_NUM = 10;
// 定义图的边结构体
struct ArcNode {
int adjvex; // 邻接点下标
int weight; // 权值
ArcNode* nextarc; // 指向下一个邻接点的指针
};
// 定义图的顶点结构体
struct VNode {
char data; // 顶点数据
ArcNode* firstarc; // 指向第一个邻接点的指针
};
// 定义图结构体
struct Graph {
VNode vexs[MAX_VERTEX_NUM]; // 顶点数组
int vexnum; // 顶点数
int arcnum; // 边数
bool visited[MAX_VERTEX_NUM]; // 标记数组
};
// 创建图的邻接矩阵
void createAdjMatrix(int adjMatrix[][MAX_VERTEX_NUM], int n, int e, vector<pair<int, int>> edges) {
// 初始化邻接矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
adjMatrix[i][j] = 0;
}
}
// 填充邻接矩阵
for (int k = 0; k < e; k++) {
int i = edges[k].first;
int j = edges[k].second;
adjMatrix[i][j] = 1;
}
}
// 输出邻接矩阵
void printAdjMatrix(int adjMatrix[][MAX_VERTEX_NUM], int n) {
cout << "邻接矩阵为:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
// 创建图的邻接表
void createAdjList(Graph& G, int n, int e, vector<pair<int, int>> edges) {
// 初始化图
G.vexnum = n;
G.arcnum = e;
for (int i = 0; i < n; i++) {
G.vexs[i].data = 'A' + i;
G.vexs[i].firstarc = NULL;
G.visited[i] = false;
}
// 填充邻接表
for (int k = 0; k < e; k++) {
int i = edges[k].first;
int j = edges[k].second;
ArcNode* p = new ArcNode;
p->adjvex = j;
p->nextarc = G.vexs[i].firstarc;
G.vexs[i].firstarc = p;
}
}
// 输出邻接表
void printAdjList(Graph G) {
cout << "邻接表为:" << endl;
for (int i = 0; i < G.vexnum; i++) {
cout << G.vexs[i].data;
ArcNode* p = G.vexs[i].firstarc;
while (p != NULL) {
cout << "->" << G.vexs[p->adjvex].data;
p = p->nextarc;
}
cout << endl;
}
cout << endl;
}
// 销毁邻接表
void destroyAdjList(Graph& G) {
for (int i = 0; i < G.vexnum; i++) {
ArcNode* p = G.vexs[i].firstarc;
while (p != NULL) {
ArcNode* q = p->nextarc;
delete p;
p = q;
}
G.vexs[i].firstarc = NULL;
G.visited[i] = false;
}
}
int main() {
// 建立如图1所示的有向图G的邻接矩阵,并输出
int n = 6; // 顶点数
int e = 9; // 边数
vector<pair<int, int>> edges = { {0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 1}, {3, 5}, {4, 3}, {4, 5}, {5, 2} };
int adjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
createAdjMatrix(adjMatrix, n, e, edges);
printAdjMatrix(adjMatrix, n);
// 建立如图1所示的有向图G的邻接表,并输出
Graph G;
createAdjList(G, n, e, edges);
printAdjList(G);
// 销毁图G的邻接表
destroyAdjList(G);
return 0;
}
```
这个程序创建了一个有向图G,顶点数为6,边数为9,边的信息存储在一个vector中。其中,createAdjMatrix函数用于创建邻接矩阵,createAdjList函数用于创建邻接表,printAdjMatrix和printAdjList函数用于输出邻接矩阵和邻接表,destroyAdjList函数用于销毁邻接表。在主函数中,分别调用这些函数实现了所需功能。