C++编程创建无向图的邻接表、有向图的邻接表和逆邻接表
时间: 2024-01-01 19:23:17 浏览: 81
以下是C++编程创建无向图的邻接表、有向图的邻接表和逆邻接表的示例代码:
1. 创建无向图的邻接表:
```cpp
#include <iostream>
#include <list>
using namespace std;
class Graph {
int V;
list<int> *adj;
public:
Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void addEdge(int v, int w) {
adj[v].push_back(w);
adj[w].push_back(v);
}
void printAdjList() {
for (int v = 0; v < V; ++v) {
cout << "Adjacency list of vertex " << v << ": ";
for (auto it = adj[v].begin(); it != adj[v].end(); ++it)
cout << *it << " ";
cout << endl;
}
}
};
int main() {
int V = 5;
Graph g(V);
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.printAdjList();
return 0;
}
```
2. 创建有向图的邻接表和逆邻接表:
```cpp
#include <iostream>
#include <list>
using namespace std;
class Graph {
int V;
list<int> *adj;
list<int> *revAdj;
public:
Graph(int V) {
this->V = V;
adj = new list<int>[V];
revAdj = new list<int>[V];
}
void addEdge(int v, int w) {
adj[v].push_back(w);
revAdj[w].push_back(v);
}
void printAdjList() {
cout << "Adjacency list:" << endl;
for (int v = 0; v < V; ++v) {
cout << "Vertex " << v << ": ";
for (auto it = adj[v].begin(); it != adj[v].end(); ++it)
cout << *it << " ";
cout << endl;
}
cout << endl;
cout << "Reverse adjacency list:" << endl;
for (int v = 0; v < V; ++v) {
cout << "Vertex " << v << ": ";
for (auto it = revAdj[v].begin(); it != revAdj[v].end(); ++it)
cout << *it << " ";
cout << endl;
}
}
};
int main() {
int V = 5;
Graph g(V);
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.printAdjList();
return 0;
}
```
阅读全文