任选一个存储结构存储一个无向图,要求最少8个顶点,12个活动,完成如下功能: 1.创建图。接收从键盘输入的边信息,存储到图中。 2.增加边的信息 3.删除边的信息。 4.对图进行深度优先遍历。
时间: 2023-06-12 21:06:02 浏览: 168
aaa.rar_无向图 环_无向图所有环_无向图最小环_最小生成树_树所有操作
我建议使用邻接表作为存储结构,以下是实现功能的代码:
```c++
#include<iostream>
#include<vector>
using namespace std;
// 邻接表结构体
struct AdjListNode {
int dest;
struct AdjListNode* next;
};
// 图结构体
struct Graph {
int V; // 顶点数
vector<AdjListNode*> adjList; // 邻接表
};
// 创建新的邻接表节点
AdjListNode* newAdjListNode(int dest) {
AdjListNode* newNode = new AdjListNode;
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// 创建图
Graph* createGraph(int V) {
Graph* graph = new Graph;
graph->V = V;
// 创建空的邻接表
for (int i = 0; i < V; ++i) {
graph->adjList.push_back(NULL);
}
return graph;
}
// 添加边
void addEdge(Graph* graph, int src, int dest) {
// 添加起点为src,终点为dest的边
AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->adjList[src];
graph->adjList[src] = newNode;
// 添加起点为dest,终点为src的边
newNode = newAdjListNode(src);
newNode->next = graph->adjList[dest];
graph->adjList[dest] = newNode;
}
// 删除边
void deleteEdge(Graph* graph, int src, int dest) {
// 删除起点为src,终点为dest的边
AdjListNode* temp = graph->adjList[src];
if (temp != NULL) {
if (temp->dest == dest) {
graph->adjList[src] = temp->next;
delete temp;
}
else {
while (temp->next != NULL && temp->next->dest != dest) {
temp = temp->next;
}
if (temp->next != NULL) {
AdjListNode* delNode = temp->next;
temp->next = delNode->next;
delete delNode;
}
}
}
// 删除起点为dest,终点为src的边
temp = graph->adjList[dest];
if (temp != NULL) {
if (temp->dest == src) {
graph->adjList[dest] = temp->next;
delete temp;
}
else {
while (temp->next != NULL && temp->next->dest != src) {
temp = temp->next;
}
if (temp->next != NULL) {
AdjListNode* delNode = temp->next;
temp->next = delNode->next;
delete delNode;
}
}
}
}
// 深度优先遍历
void DFSUtil(Graph* graph, int v, vector<bool>& visited) {
visited[v] = true;
cout << v << " ";
// 递归访问与v相邻的未访问节点
AdjListNode* temp = graph->adjList[v];
while (temp != NULL) {
int adjV = temp->dest;
if (!visited[adjV]) {
DFSUtil(graph, adjV, visited);
}
temp = temp->next;
}
}
void DFS(Graph* graph) {
vector<bool> visited(graph->V, false); // 记录每个节点是否被访问过
for (int i = 0; i < graph->V; ++i) {
if (!visited[i]) {
DFSUtil(graph, i, visited);
}
}
}
int main() {
Graph* graph = createGraph(8);
// 添加边
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
addEdge(graph, 5, 6);
addEdge(graph, 5, 7);
addEdge(graph, 6, 7);
// 删除边
deleteEdge(graph, 1, 4);
deleteEdge(graph, 5, 7);
// 深度优先遍历
cout << "深度优先遍历结果:" << endl;
DFS(graph);
return 0;
}
```
阅读全文