用c++编写程序,设无向图G有n个顶点e条边,写一算法建立G的邻接多重表,要求该算法时间复杂性为O(n+e),且除邻接多重表本身所占空间之外只用O(1)辅助空间。打印出邻接多重表
时间: 2024-02-03 22:02:30 浏览: 80
要打印出无向图G的邻接多重表,可以在建立邻接多重表的基础上,添加一个函数来遍历并输出邻接多重表的内容。以下是完整的实现:
```cpp
#include <iostream>
using namespace std;
struct Vertex {
int data;
struct EdgeNode* firstEdge;
};
struct EdgeNode {
int adjVertex1;
int adjVertex2;
struct EdgeNode* nextEdge1;
struct EdgeNode* nextEdge2;
};
void createAdjacencyList(struct Vertex* graph, int n, int e) {
for (int i = 0; i < n; i++) {
graph[i].data = i; // 初始化顶点数据
graph[i].firstEdge = nullptr; // 初始化边链表
int vertex1, vertex2;
for (int j = 0; j < e; j++) {
cin >> vertex1 >> vertex2; // 输入边的两个顶点
// 创建边结点
struct EdgeNode* newEdge1 = new struct EdgeNode;
newEdge1->adjVertex1 = vertex1;
newEdge1->adjVertex2 = vertex2;
newEdge1->nextEdge1 = nullptr;
newEdge1->nextEdge2 = nullptr;
struct EdgeNode* newEdge2 = new struct EdgeNode;
newEdge2->adjVertex1 = vertex2;
newEdge2->adjVertex2 = vertex1;
newEdge2->nextEdge1 = nullptr;
newEdge2->nextEdge2 = nullptr;
// 将边结点插入到邻接多重表中
if (graph[i].firstEdge == nullptr) {
graph[i].firstEdge = newEdge1;
newEdge1->nextEdge1 = newEdge2;
} else {
struct EdgeNode* temp = graph[i].firstEdge;
while (temp->nextEdge1 != nullptr) {
temp = temp->nextEdge1;
}
temp->nextEdge1 = newEdge1;
newEdge1->nextEdge1 = newEdge2;
}
}
}
}
void printAdjacencyList(struct Vertex* graph, int n) {
for (int i = 0; i < n; i++) {
cout << "Vertex " << i << ": ";
struct EdgeNode* temp = graph[i].firstEdge;
while (temp != nullptr) {
cout << "(" << temp->adjVertex1 << ", " << temp->adjVertex2 << ") ";
temp = temp->nextEdge1;
}
cout << endl;
}
}
int main() {
int n, e;
cout << "Enter the number of vertices and edges: ";
cin >> n >> e; // 输入顶点数和边数
struct Vertex* graph = new struct Vertex[n];
cout << "Enter the edges (vertex1 vertex2):" << endl;
createAdjacencyList(graph, n, e);
cout << "Adjacency List:" << endl;
printAdjacencyList(graph, n);
return 0;
}
```
你可以根据具体的顶点数和边数,按照提示输入边的信息,然后程序将会打印出邻接多重表的内容。注意,以上代码仅为示例,需要根据实际需求进行修改和完善。
阅读全文