任选一个存储结构存储一个无向图,要求最少8个顶点,12个边,完成如下功能: 1.创建图。接收从键盘输入的边信息,存储到图中。 2.增加边的信息。 3.删除边的信息。 4.对图进行深度优先遍历。使用c语言实现
时间: 2024-05-03 18:20:23 浏览: 62
aaa.rar_无向图 环_无向图所有环_无向图最小环_最小生成树_树所有操作
可以使用邻接表作为存储结构来存储无向图,以下是代码实现:
```
#include<stdio.h>
#include<stdlib.h>
//定义邻接表结构体
typedef struct node{
int vertex; //图中的顶点
struct node* next; //指向下一个邻接点的指针
}Node;
//定义图结构体
typedef struct graph{
int V; //图中的顶点数
int E; //图中的边数
Node** adjList; //指向邻接表头指针的指针
}Graph;
//创建邻接表节点
Node* createNode(int v){
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
//创建图
Graph* createGraph(int V){
Graph* graph = (Graph*) malloc(sizeof(Graph));
graph->V = V;
graph->E = 0;
graph->adjList = (Node**) malloc(V * sizeof(Node*));
//将所有邻接表头指针初始化为NULL
int i;
for(i=0;i<V;i++){
graph->adjList[i] = NULL;
}
return graph;
}
//增加边的信息
void addEdge(Graph* graph, int src, int dest){
//在邻接表src处添加dest节点
Node* newNode = createNode(dest);
newNode->next = graph->adjList[src];
graph->adjList[src] = newNode;
//在邻接表dest处添加src节点
newNode = createNode(src);
newNode->next = graph->adjList[dest];
graph->adjList[dest] = newNode;
//更新边数
graph->E++;
}
//删除边的信息
void deleteEdge(Graph* graph, int src, int dest){
//从邻接表src中删除dest节点
Node* temp = graph->adjList[src];
if(temp->vertex == dest){
graph->adjList[src] = temp->next;
free(temp);
}
else{
while(temp->next->vertex != dest){
temp = temp->next;
}
Node* temp2 = temp->next;
temp->next = temp2->next;
free(temp2);
}
//从邻接表dest中删除src节点
temp = graph->adjList[dest];
if(temp->vertex == src){
graph->adjList[dest] = temp->next;
free(temp);
}
else{
while(temp->next->vertex != src){
temp = temp->next;
}
Node* temp2 = temp->next;
temp->next = temp2->next;
free(temp2);
}
//更新边数
graph->E--;
}
//对图进行深度优先遍历
void DFS(Graph* graph, int v, int* visited){
visited[v] = 1; //标记当前节点已访问
printf("%d ", v); //打印当前节点
Node* temp = graph->adjList[v];
while(temp != NULL){
int adjVertex = temp->vertex;
if(!visited[adjVertex]){ //如果邻接点未被访问,则递归访问
DFS(graph, adjVertex, visited);
}
temp = temp->next;
}
}
int main(){
Graph* graph = createGraph(8);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 5);
addEdge(graph, 2, 6);
addEdge(graph, 3, 7);
addEdge(graph, 4, 7);
addEdge(graph, 5, 7);
addEdge(graph, 6, 7);
printf("图的邻接表表示:\n");
int i;
for(i=0;i<graph->V;i++){
printf("%d -> ", i);
Node* temp = graph->adjList[i];
while(temp != NULL){
printf("%d ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
printf("删除(3,7)边后的邻接表表示:\n");
deleteEdge(graph, 3, 7);
for(i=0;i<graph->V;i++){
printf("%d -> ", i);
Node* temp = graph->adjList[i];
while(temp != NULL){
printf("%d ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
printf("深度优先遍历结果:");
int visited[8] = {0};
DFS(graph, 0, visited);
printf("\n");
return 0;
}
```
阅读全文