思路:
1. 使用两个文件 arc 和 vex 分别存放 节点和弧信息
存放格式为:
typedef struct data{ char placename[NAMEMAX]; char placedata[DATAMAX]; }Data; typedef struct arc{ int forvex; int backves; int weight; }Arc;//文件存储结构体
2. 为了方便删除和添加,使用邻接表,邻接表的结构体
typedef struct arcnode{ int adjvex; int weight; struct arcnode* next; }ArcNode; typedef struct vertexnode{ Data vexdata; ArcNode * next; }VertxNode; typedef struct { VertxNode vertex[NUMMAX]; int vexnum; int arcnum; }ListMatrix;
3. 为了方便操做和模块化,将地图的节点和弧的添加分别抽象成模块
int AddArc( ListMatrix * G ) /* * 增加弧 * 成功返回1 * 失败返回0 */ { char forvextemp[NAMEMAX]; char backvextemp[NAMEMAX]; int forvex; int backvex; ArcNode * temp; ArcNode * p; printf("输入起始点:"); scanf("%s",forvextemp); if( (forvex = NametoNum( G, forvextemp )) == 0 ) { return 0; } printf("输入终点:"); scanf("%s",backvextemp); if( (backvex = NametoNum( G,backvextemp)) == 0 ) { return 0; }//读取起点和终点 G->arcnum++;//弧数加一 temp = (ArcNode*)malloc(sizeof(ArcNode)); printf("输入路径长度:"); scanf("%d",&temp->weight); temp->adjvex = backvex; temp->next = NULL;//赋值 p = G->vertex[forvex].next; while( p&&p->next ) p = p->next; if( !p ) G->vertex[forvex].next = p; else p->next = temp; //挂链 return 1; }
4.整个程序,只有在开始时读 arc vex 文件,建立map,在退出时写文件,将可能被修改过的map,覆盖写入 arc vex 文件
其他所有操作都建立在内存中的map,不再对文件进行操作
int MakeMap( ListMatrix *G ) /* * 利用文件建立地图 * 输入存放节点的文件 fp1 ,存放弧的文件fp2 * */ { FILE * fp1; FILE * fp2; int nodecount = 0; int arccount = 0; Data nodedata; Arc arcdata; ArcNode * p; ArcNode * temp; if( (fp1=fopen("vex","ab+")) == NULL ) { printf("vex打开错误"); return 0; } if( (fp2=fopen("arc","ab+")) == NULL ) { printf("arc打开错误\n"); return 0; } while( fread(&nodedata,sizeof(Data),1,fp1) == 1 ) { nodecount++; strcpy(G->vertex[nodecount].vexdata.placename,nodedata.placename); strcpy(G->vertex[nodecount].vexdata.placedata,nodedata.placedata); G->vertex[nodecount].next = NULL; }//读取节点 if( nodecount != 0 ) { while( fread( &arcdata,sizeof(Arc),1,fp2) == 1 ) { arccount++; temp->next = ( ArcNode *)malloc(sizeof(ArcNode)); temp->next->adjvex = arcdata.backves; temp->next->weight = arcdata.weight; temp->next->next = NULL; p = G->vertex[arcdata.forvex].next; while( p && p->next ) p = p->next; if( !p ) G->vertex[arcdata.forvex].next = temp; else p->next =temp;//挂链 } }//读取弧 G->vexnum = nodecount; G->arcnum = arccount; fclose(fp1); fclose(fp2); }
时间: 2024-09-30 14:49:16