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 128 129 130 131 132 133 134 135 136 137 138 139
| #include <stdio.h> #include <stdlib.h>
#define MAXVEX 100 #define INFINITY 65535
typedef char VertexType; typedef int EdgeType; typedef int InforType;
typedef struct EdgeNode { int adjvex; EdgeType weight; struct EdgeNode *next; }EdgeNode;
typedef struct VertexNode { VertexType data; EdgeNode *firstedge; }VertexNode;
typedef struct GraphAdjlist { VertexNode adjlist[MAXVEX]; int numVertex, numEdge; }GraphList;
int Locate(GraphList *g, char ch) { int i; for(i = 0; i < MAXVEX && ch != g->adjlist[i].data; i++) ; if(i >= MAXVEX) { printf("There is no this vertex !\n"); return -1; } return i; }
void CreatGraphList(GraphList *g) { EdgeNode *e; EdgeNode *f; int i, k; printf("输入顶点数和边数:\n"); scanf("%d,%d", &(g->numVertex), &(g->numEdge)); for(i = 0; i < g->numVertex; i++) { printf("请输入顶点%d: \n", i); g->adjlist[i].data = getchar(); g->adjlist[i].firstedge = NULL; while(g->adjlist[i].data == '\n') g->adjlist[i].data = getchar(); } for(k = 0; k < g->numEdge; k++) { printf("输入边(vi,vj)上的顶点序号:\n"); char p, q; scanf("%c %c", &p, &q); getchar(); int m = Locate(g, p); int n = Locate(g, q); if(m == -1 || n == -1) return ; e = (EdgeNode *)malloc(sizeof(EdgeNode)); if(!e) {printf("malloc() error !\n"); return ;} e->adjvex = n; e->next = g->adjlist[m].firstedge; g->adjlist[m].firstedge = e;
f = (EdgeNode *)malloc(sizeof(EdgeNode)); if(!e) {printf("malloc() error !\n"); return ;} f->adjvex = m; f->next = g->adjlist[n].firstedge; g->adjlist[n].firstedge = f; } }
void DFS(GraphList g, int i) { EdgeNode *p; visited[i] = true; printf("%c ", g->adjlist[i].data); p = g->adjlist[i].firstedge; while(p) { if(!visited[p->adjvex]) { DFS(g, p->adjvex); } p = p->next; } }
void DFSTraverse(GraphList g) { int i; for(i = 0; i <g.numVertex; i++) visited[i] = false; for(i = 0; i < g.numVertex; i++) { if(!visited[i]) DFS(g, i); }
}
void printGraph(GraphList *g) { int i = 0; while(g->adjlist[i].firstedge != NULL && i < MAXVEX) { printf("顶点: %c", g->adjlist[i].data); EdgeNode *e = NULL; e = g->adjList[i].firstedge; while(e != NULL) { printf("%d ", e->adjvex); e = e->next; } i++; printf("\n"); } }
int main() { GraphList g; CreatGraph(&g); print(&g); return 0; }
|