1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
#include <stdio.h> #include <stdlib.h>
#define MAXVEX 100
typedef char VertexType; typedef int EdgeType;
typedef struct edgeNode { int adjvex; EdgeType weight; struct edgeNode * next; } EdgeNode;
typedef struct vertexNode { VertexType data; EdgeNode * firstEdge; } VertexNode;
typedef VertexNode AdjList[MAXVEX];
typedef struct { AdjList adjList; int numVex, numEdge; } ALGraph;
void CreateALGraph(ALGraph *G);
int main(void) { ALGraph G;
CreateALGraph(&G);
printf("顶点数: %d,边数: %d\n", G.numVex, G.numEdge);
VertexType v0 = G.adjList[0].data; int idx = G.adjList[0].firstEdge->adjvex; EdgeType w1 = G.adjList[0].firstEdge->weight; VertexType v1 = G.adjList[idx].data; printf("边(%c,%c)的权值: %d\n", v0, v1, w1);
VertexType v2 = G.adjList[2].data; int idx2 = G.adjList[2].firstEdge->adjvex; EdgeType w2 = G.adjList[2].firstEdge->weight; VertexType v3 = G.adjList[idx].data; printf("边(%c,%c)的权值: %d\n", v2, v3, w2); return 0; }
void CreateALGraph(ALGraph *G) { int i, j, k, w;
printf("请输入顶点数和边数(以空格分割):"); scanf("%d %d", &G->numVex, &G->numEdge); while( getchar() != '\n' );
printf("请输入顶点信息(连续输入,勿空格):"); for ( i = 0; i < G->numVex; i++ ) { scanf("%c", &G->adjList[i].data); G->adjList[i].firstEdge = NULL; } while( getchar() != '\n' );
for ( k = 0; k < G->numEdge; k++ ) { printf("请输入边(Vi,Vj)的下标i、小标j和权值(以空格分割):"); scanf("%d %d %d", &i, &j, &w); EdgeNode * e = (EdgeNode*)malloc(sizeof(EdgeNode)); if ( NULL == e) { printf("内存分配失败!"); exit(-1); } e->weight = w; e->adjvex = j; e->next = G->adjList[i].firstEdge; G->adjList[i].firstEdge = e;
e = (EdgeNode*)malloc(sizeof(EdgeNode)); if ( NULL == e) { printf("内存分配失败!"); exit(-1); } e->weight = w; e->adjvex = i; e->next = G->adjList[j].firstEdge; G->adjList[j].firstEdge = e; } }
|