邻接表1
试在邻接表存储结构上实现图的基本操作 insert_vertex 和 insert_arc,相关定义如下:
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 insert_vertex(ListGraph *G, VertexType v);
bool insert_arc(ListGraph *G, VertexType v, VertexType w);
当成功插入顶点或边时,函数返回true,否则(如顶点或边已存在、插入边时顶点v或w不存在)返回false。
参考答案如下:
#include <stdio.h>
#include<stdlib.h>
//记得加这个头文件消除黄色警告
#include "graph.h" //请勿删除,否则检查不通过
bool insert_vertex(ListGraph *G, VertexType v){int n;n = locate_vertex(G, v);if(n == -1){//if(G->type == DG || G->type == UDG){G->vertex[G->vexnum].data = v;G->vertex[G->vexnum].firstarc = NULL;G->vexnum++;return true;}elsereturn false;}bool insert_arc(ListGraph *G, VertexType v, VertexType w){int i, j;ArcNode *p;i = locate_vertex(G, v);j = locate_vertex(G, w);//判结点是否存在,不存在就返回false if(i == -1|| j == -1)return false;//判边是否存在,存在就返回false //需要注意的是p->adjvex = j这个判断条件,一个是int类型,一个是不要把这个判断条件放到for里面 for(p = G->vertex[i].firstarc; p; p = p->nextarc)if(p->adjvex == j) return false;//!!!!!需要注意的是这里是单项插入,不考虑有向无向//插入到方向就是v-->w
// for(p = G->vertex[j].firstarc; p; p = p->nextarc)
// if(p->adjvex == i) return false;// if(G->type == UDG){
// p->nextarc = G->vertex[j].firstarc->nextarc;
// p->adjvex = v;
// G->vertex[j].firstarc = p;
// }//!!!别忘了分配空间,这个是建立一个新的节点 p = (ArcNode *)malloc(sizeof(ArcNode));p->adjvex = j;G->arcnum++; if(!G->vertex[i].firstarc)//空的情况 G->vertex[i].firstarc = p;else{//头插 p->nextarc = G->vertex[i].firstarc->nextarc;G->vertex[i].firstarc = p;}return true;
}
欢迎留言讨论哦!