邻接表创建有向图代码
时间: 2023-12-03 18:04:12 浏览: 73
有向图的构建(邻接表)
5星 · 资源好评率100%
以下是使用邻接表创建有向图的代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义邻接表中的边结构体
struct EdgeNode {
int to; // 边的终点
int weight; // 边的权重
EdgeNode *next; // 指向下一条边的指针
EdgeNode(int t, int w) : to(t), weight(w), next(nullptr) {}
};
// 定义邻接表中的顶点结构体
struct VertexNode {
char data; // 顶点数据
EdgeNode *first_edge; // 指向第一条边的指针
VertexNode(char c) : data(c), first_edge(nullptr) {}
};
// 定义有向图结构体
struct Graph {
int n; // 顶点数
vector<VertexNode> adj_list; // 邻接表
Graph(int num) : n(num), adj_list(n, VertexNode(' ')) {}
};
// 添加一条边
void addEdge(Graph *graph, int from, int to, int weight) {
EdgeNode *edge = new EdgeNode(to, weight);
edge->next = graph->adj_list[from].first_edge;
graph->adj_list[from].first_edge = edge;
}
// 创建有向图
Graph* createGraph() {
int n, m;
cout << "请输入顶点数和边数:";
cin >> n >> m;
Graph *graph = new Graph(n);
cout << "请输入每个顶点的数据:";
for (int i = 0; i < n; ++i) {
cin >> graph->adj_list[i].data;
}
cout << "请输入每条边的起点、终点和权重:" << endl;
for (int i = 0; i < m; ++i) {
int from, to, weight;
cin >> from >> to >> weight;
addEdge(graph, from, to, weight);
}
return graph;
}
// 打印有向图
void printGraph(Graph *graph) {
cout << "有向图的邻接表如下:" << endl;
for (int i = 0; i < graph->n; ++i) {
cout << i << "(" << graph->adj_list[i].data << "): ";
EdgeNode *edge = graph->adj_list[i].first_edge;
while (edge != nullptr) {
cout << edge->to << "(" << graph->adj_list[edge->to].data << "," << edge->weight << ") ";
edge = edge->next;
}
cout << endl;
}
}
// 主函数
int main() {
Graph *graph = createGraph();
printGraph(graph);
return 0;
}
```
阅读全文