void DeleteVertex(ALGraph *G) { int i, j; printf("请输入要删除的顶点下标:"); scanf("%d", &i);
时间: 2024-01-09 19:04:44 浏览: 51
首先,这个函数的目的是删除一个顶点及其相关的边。下面是代码的完整实现:
```c
void DeleteVertex(ALGraph *G) {
int i, j;
printf("请输入要删除的顶点下标:");
scanf("%d", &i);
if (i < 0 || i >= G->vexnum) {
printf("输入的顶点下标不合法!\n");
return;
}
// 删除该顶点的出边
ArcNode *p = G->vertices[i].firstarc;
while (p) {
ArcNode *q = p->nextarc;
int k = p->adjvex;
// 删除入边
ArcNode *r = G->vertices[k].firstarc;
ArcNode *s = NULL;
while (r && r->adjvex != i) {
s = r;
r = r->nextarc;
}
if (r && s) {
s->nextarc = r->nextarc;
free(r);
} else if (r) {
G->vertices[k].firstarc = r->nextarc;
free(r);
}
free(p);
p = q;
G->arcnum--;
}
G->vertices[i].firstarc = NULL;
// 删除该顶点的入边
for (j = 0; j < G->vexnum; j++) {
if (j == i) continue;
p = G->vertices[j].firstarc;
ArcNode *s = NULL;
while (p && p->adjvex != i) {
s = p;
p = p->nextarc;
}
if (p && s) {
s->nextarc = p->nextarc;
free(p);
G->arcnum--;
} else if (p) {
G->vertices[j].firstarc = p->nextarc;
free(p);
G->arcnum--;
}
}
// 删除该顶点
for (j = i; j < G->vexnum - 1; j++) {
G->vertices[j] = G->vertices[j+1];
}
G->vexnum--;
printf("删除顶点成功!\n");
}
```
首先,输入要删除的顶点下标,检查输入是否合法。然后遍历该顶点的出边,对于每一条出边,找到其指向的顶点,删除该顶点到当前顶点的入边,最后删除该出边。接着遍历整张图的每个顶点,删除指向该顶点的所有入边。最后删除该顶点。
阅读全文