邻接表

来源:互联网 发布:ios 类似淘宝购物车 编辑:程序博客网 时间:2024/04/29 04:53
#include<stdio.h>#include<stdlib.h>#define MAXVEX 100//边表结点 typedef struct node{int adjvex;//邻接点域char adjweg;//struct node *next; }EdgeNode;//顶点表结点 typedef struct Vnode{char vertex;//顶点域EdgeNode *firstedge; }VexNode;//AdjList是邻接表类型typedef VexNode AdjList[MAXVEX]; typedef struct {AdjList adlist;//邻接表int n, e;//当前顶点数和边数}ALGraph;void CreatALGraph(ALGraph *G){int i, j, k;EdgeNode *p;printf("输入顶点数和边数:\n");scanf("%d%d", &G->n, &G->e);//建立顶点表printf("输入顶点信息:\n");for(i=0; i<G->n; i++){getchar();scanf("%c", &G->adlist[i].vertex);//读入顶点信息G->adlist[i].firstedge = NULL;//边表置为空表}//for(i=0; i<G->n; i++){//printf("%c ", G->adlist[i].vertex);//}//建立边表for(k=0; k<G->e; k++){printf("输入第%d条边的顶点对序号\n", k+1);scanf("%d%d", &i, &j);//生成边表结点,为边头结点p = (EdgeNode *)malloc(sizeof(EdgeNode));p->next = NULL;p->adjvex = j; p->adjweg = G->adlist[j].vertex;//将新结点p插入顶点Vi的边表头部p->next = G->adlist[i].firstedge;G->adlist[i].firstedge = p;p = (EdgeNode *)malloc(sizeof(EdgeNode));p->next = NULL;p->adjvex = i;p->adjweg = G->adlist[i].vertex;//将新结点p插入顶点Vj的边表头部p->next = G->adlist[j].firstedge;G->adlist[j].firstedge = p;}}void PrintALGraph(ALGraph *G){int i;EdgeNode *p;for(i=0; i<G->n; i++){printf("%c ", G->adlist[i].vertex);p = G->adlist[i].firstedge;if(p == NULL) {printf("\n");continue;} while(1){//printf("%d ", p->adjvex);printf("%c ", p->adjweg);if(p->next == NULL) {printf("\n");break;} p = p->next;}}}main(){ALGraph *G;G = (ALGraph *)malloc(sizeof(ALGraph));CreatALGraph(G);PrintALGraph(G);}

原创粉丝点击