无向图邻接表删除边C语言
时间: 2024-05-26 14:06:15 浏览: 80
以下是在无向图邻接表中删除边的C语言示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct Node {
int vertex;
struct Node* next;
} Node;
typedef struct Graph {
Node* adjList[MAX_VERTICES];
int numVertices;
} Graph;
// 初始化图
void initGraph(Graph* graph, int numVertices) {
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
graph->adjList[i] = NULL;
}
}
// 添加边
void addEdge(Graph* graph, int u, int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = graph->adjList[u];
graph->adjList[u] = newNode;
newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = u;
newNode->next = graph->adjList[v];
graph->adjList[v] = newNode;
}
// 删除边
void deleteEdge(Graph* graph, int u, int v) {
Node* curr = graph->adjList[u];
Node* prev = NULL;
// 遍历链表,找到要删除的边
while (curr != NULL && curr->vertex != v) {
prev = curr;
curr = curr->next;
}
// 如果找到了要删除的边
if (curr != NULL) {
// 如果要删除的边是链表的第一个节点
if (prev == NULL) {
graph->adjList[u] = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
}
// 同样的操作,删除另一条边
curr = graph->adjList[v];
prev = NULL;
while (curr != NULL && curr->vertex ! u) {
prev = curr;
curr = curr->next;
}
if (curr != NULL) {
if (prev == NULL) {
graph->adjList[v] = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
}
}
// 打印图的邻接表
void printGraph(Graph* graph) {
for (int i = 0; i < graph->numVertices; i++) {
Node* curr = graph->adjList[i];
printf("Vertex %d: ", i);
while (curr != NULL) {
printf("%d -> ", curr->vertex);
curr = curr->next;
}
printf("NULL\n");
}
}
int main() {
Graph graph;
int numVertices = 5;
initGraph(&graph, numVertices);
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 1, 2);
addEdge(&graph, 2, 3);
addEdge(&graph, 3, 4);
printf("Before deleting edge:\n");
printGraph(&graph);
deleteEdge(&graph, 0, 2);
printf("\nAfter deleting edge:\n");
printGraph(&graph);
return 0;
}
```
阅读全文