基于邻接表建立图cpp
时间: 2023-07-04 15:23:18 浏览: 63
同样是邻接表的实现,这里给出C++的实现例子:
```cpp
#include <iostream>
#include <vector>
using namespace std;
struct Edge {
int dest;
Edge* next;
};
class Graph {
public:
Graph(int n) : numVertices(n), adjList(n, nullptr) {}
void addEdge(int src, int dest) {
Edge* newEdge = new Edge{ dest, adjList[src] };
adjList[src] = newEdge;
newEdge = new Edge{ src, adjList[dest] };
adjList[dest] = newEdge;
}
void printGraph() {
for (int i = 0; i < numVertices; i++) {
Edge* temp = adjList[i];
cout << "Vertex " << i << ": ";
while (temp) {
cout << temp->dest << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
}
private:
int numVertices;
vector<Edge*> adjList;
};
// 测试
int main() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.printGraph();
return 0;
}
```
与C的实现类似,这里也定义了一个`Edge`结构体来表示边,另外定义了一个`Graph`类来表示整个图。在`addEdge`函数中,我们添加从一个顶点到另一个顶点的边,同时也添加从另一个顶点到该顶点的边。在`printGraph`函数中,我们打印邻接表。最后,在`main`函数中,我们创建了一个新的图并添加了一些边,然后打印邻接表。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)