无向图以邻接表存储,试编写图的基本运算(输入两顶点序号插入边、输入两顶点序号查找是否存在边)。用c语言实现
时间: 2024-12-22 14:27:02 浏览: 25
在无向图的邻接表存储中,我们通常会为每个顶点维护一个链表,链表中的节点表示与该顶点相连的其他顶点。以下是使用C语言实现无向图的一些基本操作:
1. 结构体定义:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int vertex;
struct Node* next;
} Edge;
typedef struct Graph {
int vertices; // 顶点数
Edge** adj; // 邻接表数组
} Graph;
```
2. 初始化和删除函数:
```c
void createGraph(Graph* graph, int vertices) {
graph->vertices = vertices;
graph->adj = (Edge**)malloc(sizeof(Edge*) * vertices);
for (int i = 0; i < vertices; ++i) {
graph->adj[i] = NULL;
}
}
void deleteGraph(Graph* graph) {
for (int i = 0; i < graph->vertices; ++i) {
if (graph->adj[i]) {
free(graph->adj[i]);
}
}
free(graph->adj);
}
```
3. 插入边函数(假设两个顶点已存在):
```c
void addEdge(Graph* graph, int src, int dest) {
Edge* newNode = (Edge*)malloc(sizeof(Edge));
newNode->vertex = dest;
newNode->next = graph->adj[src];
graph->adj[src] = newNode;
// 如果dest还没有从src指向,则添加反向链接
if (graph->adj[dest] == NULL) {
newNode = (Edge*)malloc(sizeof(Edge));
newNode->vertex = src;
newNode->next = graph->adj[dest];
graph->adj[dest] = newNode;
}
}
```
4. 检查边是否存在:
```c
int isAdjacent(Graph* graph, int src, int dest) {
Edge* current = graph->adj[src];
while (current != NULL) {
if (current->vertex == dest) {
return 1; // 存在边
}
current = current->next;
}
return 0; // 不存在边
}
```
阅读全文