.任选一个存储结构存储一个无向图,要求最少8个顶点,12个活动,完成如下功能: 1.创建图。接收从键盘输入的边信息,存储到图中。 2.增加边的信息。 3.删除边的信息。 4.对图进行深度优先遍历。
时间: 2023-06-27 19:06:15 浏览: 78
邻接表或者邻接矩阵为存储结构实现连通无向图的深度优先和广度优先遍历
3星 · 编辑精心推荐
我会选择使用邻接表来存储这个无向图,以下是实现上述功能的代码:
```c++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
struct Edge {
int dest;
Edge* next;
Edge(int d) : dest(d), next(NULL) {}
};
class Graph {
private:
int V; // 顶点数
vector<Edge*> adj; // 邻接表
public:
Graph(int V) : V(V), adj(V, NULL) {}
void addEdge(int src, int dest) {
Edge* newEdge = new Edge(dest);
newEdge->next = adj[src];
adj[src] = newEdge;
newEdge = new Edge(src);
newEdge->next = adj[dest];
adj[dest] = newEdge;
}
void deleteEdge(int src, int dest) {
Edge* curr = adj[src];
Edge* prev = NULL;
while (curr != NULL && curr->dest != dest) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
if (prev == NULL) adj[src] = curr->next;
else prev->next = curr->next;
delete curr;
curr = adj[dest];
prev = NULL;
while (curr != NULL && curr->dest != src) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
if (prev == NULL) adj[dest] = curr->next;
else prev->next = curr->next;
delete curr;
}
void DFS(int start) {
vector<bool> visited(V, false);
stack<int> s;
s.push(start);
while (!s.empty()) {
int v = s.top();
s.pop();
if (visited[v]) continue;
cout << v << " ";
visited[v] = true;
Edge* curr = adj[v];
while (curr != NULL) {
if (!visited[curr->dest]) {
s.push(curr->dest);
}
curr = curr->next;
}
}
}
};
int main() {
Graph g(8); // 创建一个8个顶点的图
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);
g.addEdge(2, 6);
g.addEdge(3, 7);
g.addEdge(4, 7);
g.addEdge(5, 7);
g.addEdge(6, 7);
// 添加一条边
g.addEdge(0, 3);
// 删除一条边
g.deleteEdge(1, 4);
// 进行深度优先遍历
g.DFS(0);
return 0;
}
```
这段代码创建了一个8个顶点,12条边的无向图,并实现了增加边、删除边和深度优先遍历的功能。
阅读全文