试在邻接表存储结构上实现图的基本操作 del_vertex,相关定义如下: typedef int VertexType; typedef enum{ DG, UDG }GraphType; typedef struct ArcNode{ int adjvex; InfoPtr *info; struct ArcNode *nextarc; }ArcNode; typedef struct VNode{ VertexType data; ArcNode *firstarc; }VNode; typedef struct{ VNode vertex[MAX_VERTEX_NUM]; int vexnum, arcnum; GraphType type; }ListGraph; int locate_vertex(ListGraph *G, VertexType v); //返回顶点 v 在vertex数组中的下标,如果v不存在,返回-1 bool del_vertex(ListGraph *G, VertexType v); //删除顶点 v 当成功删除顶点或边时,函数返回true,否则(如顶点或边不存在、删除边时顶点v或w不存在)返回false。
时间: 2024-03-23 18:42:35 浏览: 29
好的,我来解答你的问题。del_vertex函数的实现如下:
```c++
bool del_vertex(ListGraph *G, VertexType v) {
int i, j;
for (i = 0; i < G->vexnum; i++) {
if (G->vertex[i].data == v) {
ArcNode *p = G->vertex[i].firstarc;
while (p) {
int adjvex = p->adjvex;
ArcNode *q = G->vertex[adjvex].firstarc, *pre = NULL;
while (q) {
if (q->adjvex == i) {
if (pre == NULL) {
G->vertex[adjvex].firstarc = q->nextarc;
} else {
pre->nextarc = q->nextarc;
}
free(q);
G->arcnum--;
break;
}
pre = q;
q = q->nextarc;
}
p = p->nextarc;
}
ArcNode *q = G->vertex[i].firstarc;
while (q) {
ArcNode *tmp = q;
q = q->nextarc;
free(tmp);
G->arcnum--;
}
for (j = i; j < G->vexnum - 1; j++) {
G->vertex[j] = G->vertex[j+1];
}
G->vexnum--;
for (j = 0; j < G->vexnum; j++) {
ArcNode *p = G->vertex[j].firstarc;
while (p) {
if (p->adjvex > i) {
p->adjvex--;
}
p = p->nextarc;
}
}
return true;
}
}
return false;
}
```
其中,我们首先需要遍历邻接表中所有的顶点,找到数据域为v的顶点,然后删除该顶点的所有边。删除边的过程中,我们需要遍历所有邻接表,找到对应的边,将边从邻接表中删除,同时更新边的数量。最后,我们将所有后面的顶点向前移动一个位置,然后更新所有顶点的邻接表中与该顶点相关的顶点编号。删除顶点的过程中,我们需要删除该顶点的所有边以及对应的邻接表结点,以及更新顶点和边的数量。如果找不到数据域为v的顶点,则返回false。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)