鄰接表有向圖(一)之 C語言詳解
阿新 • • 發佈:2018-12-31
/* * 建立鄰接表對應的圖(自己輸入) */ LGraph* create_lgraph() { char c1, c2; int v, e; int i, p1, p2; ENode *node1, *node2; LGraph* pG; // 輸入"頂點數"和"邊數" printf("input vertex number: "); scanf("%d", &v); printf("input edge number: "); scanf("%d", &e); if ( v < 1 || e < 1 || (e > (v * (v-1)))) { printf("input error: invalid parameters!\n"); return NULL; } if ((pG=(LGraph*)malloc(sizeof(LGraph))) == NULL ) return NULL; memset(pG, 0, sizeof(LGraph)); // 初始化"頂點數"和"邊數" pG->vexnum = v; pG->edgnum = e; // 初始化"鄰接表"的頂點 for(i=0; i<pG->vexnum; i++) { printf("vertex(%d): ", i); pG->vexs[i].data = read_char(); pG->vexs[i].first_edge = NULL; } // 初始化"鄰接表"的邊 for(i=0; i<pG->edgnum; i++) { // 讀取邊的起始頂點和結束頂點 printf("edge(%d): ", i); c1 = read_char(); c2 = read_char(); p1 = get_position(*pG, c1); p2 = get_position(*pG, c2); // 初始化node1 node1 = (ENode*)malloc(sizeof(ENode)); node1->ivex = p2; // 將node1連結到"p1所在連結串列的末尾" if(pG->vexs[p1].first_edge == NULL) pG->vexs[p1].first_edge = node1; else link_last(pG->vexs[p1].first_edge, node1); } return pG; }