无向图建立 邻接表(2)

来源:互联网 发布:天猫跟淘宝有啥区别 编辑:程序博客网 时间:2024/05/16 14:04
#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAX 100#define isLetter(a) ((((a)>='a') && ((a)<='z')) || (((a)>='A')&&((a)<='Z')))#define LENGTH(a) (sizeof(a)/sizeof(a[0]))#define TRUE 1#define FALSE 0#define bool intbool visited[MAX];typedef struct _ENode {int ivex; // 索引struct _ENode* next_edge;}ENode,*PENode;typedef struct _VNode {char data;  //顶点信息ENode *first_edge;//指向第一条依附于该顶点的弧}VNode;typedef struct _LGraph {VNode vex[MAX];int vexnum;int edgnum;}LGraph;static int get_position(LGraph g, char ch){int i;for (i = 0; i < g.vexnum; i++) {if (g.vex[i].data == ch) {return i;}}return -1;}static char read_char(){char ch;do {ch = getchar();} while (!isLetter(ch));return ch;}static void link_last(ENode * list, ENode * node){while (list->next_edge != NULL) {list = list->next_edge;}list->next_edge = node;}LGraph* create_lgraph(){char c1, c2;int v, e;int i, p1, p2;ENode* node1, *node2;LGraph* PG;//输入顶点数 边数printf("输入顶点数:\n");scanf("%d", &v);printf("输入边数:\n");scanf("%d", &e);if (v < 1 || e < 1 || e >(v*(v - 1))) {printf("error");return NULL;}if ((PG = (LGraph*)malloc(sizeof(LGraph))) == NULL)return NULL;memset(PG, 0, sizeof(LGraph));PG->vexnum = v;PG->edgnum = e;//初始化 邻接表 的顶点printf("输入顶点信息(输入后回车):\n\n");for (i = 0; i < PG->vexnum; i++) {printf("vertex(%d) :",i);PG->vex[i].first_edge = NULL;PG->vex[i].data = read_char();}//初始化 邻接表边printf("\n输入边信息:\n\n");for (i = 0; i < PG->edgnum; i++) {printf("edge (%d) ", i);c1 = read_char();c2 = read_char();if(c1 != c2){p1 = get_position(*PG, c1);p2 = get_position(*PG, c2);//初始化 node1;node1 = (ENode*)malloc(sizeof(ENode));node1->next_edge = NULL;node1->ivex = p2;if (PG->vex[p1].first_edge == NULL) {PG->vex[p1].first_edge = node1;}elselink_last(PG->vex[p1].first_edge, node1);node2 = (ENode*)malloc(sizeof(ENode));node2->ivex = p1;node2->next_edge = NULL;if (PG->vex[p2].first_edge == NULL) {PG->vex[p2].first_edge = node2;}elselink_last(PG->vex[p2].first_edge, node2);}}return PG;}void Print(LGraph pG){int i;ENode *P;for (i = 0; i < pG.vexnum; i++) {printf("Vertex %c:\n", pG.vex[i].data);P = pG.vex[i].first_edge;while (P != NULL) {printf("\t(%c,%c)", pG.vex[i].data, pG.vex[P->ivex].data);P = P->next_edge;}printf("\n");}}void DFS(LGraph g, int i){visited[i] = TRUE;printf("%c ", g.vex[i].data);ENode* p;p = g.vex[i].first_edge;while (p != NULL) {if (!visited[p->ivex])DFS(g, p->ivex);p = p->next_edge;}}void DFSTrv(LGraph g){int i;for (i = 0; i < g.vexnum; i++) {visited[i] = FALSE;}for (i = 0; i < g.vexnum; i++) {if (!visited[i]) {DFS(g, i);}}}int main(){LGraph* pG;pG = create_lgraph();Print(*pG);printf("遍历各顶点:\n");DFSTrv(*pG);getchar();getchar();return 0;}

原创粉丝点击