//採用鄰接表表示法建立無向圖 #include <iostream> using namespace std; #define MVNnm 100 #define OK 1 typedef char VerTexType; typedef int OtherInfo; typedef struct ArcNode { int adjvex; struct ArcNode* nextarc; OtherInfo info; }ArcNode; typedef struct VNode { VerTexType data; ArcNode* firstarc; }VNode, adjList[MVNnm]; typedef struct { adjList vertices; int vexnum, arcnum; }ALGraph; int LocateVex(ALGraph G, VerTexType v) { for (int i = 0;i < G.vexnum;++i) { if (G.vertices[i].data == v) { return i; } } return -1; } int CreatUDG(ALGraph& G) { int i, k; cout << "請輸入總頂點數,總邊數中間以空格隔開:"; cin >> G.vexnum >> G.arcnum; cout << endl; for (i = 0;i < G.vexnum;++i) { cout << "請輸入第" << (i + 1) << "個點的名稱:"; cin >> G.vertices[i].data; G.vertices[i].firstarc = NULL; } cout << endl; cout << "請輸入一條邊依附的頂點,如 a b" << endl; for (k = 0;k < G.arcnum;++k) { VerTexType v1, v2; int i, j; cout << "請輸入第" << (k + 1) << "條邊依附的頂點:"; cin >> v1 >> v2; i = LocateVex(G, v1); j = LocateVex(G, v2); ArcNode* p1 = new ArcNode; p1->adjvex = j; p1->nextarc = G.vertices[i].firstarc; G.vertices[i].firstarc = p1; ArcNode* p2 = new ArcNode; p2->adjvex = j; p2->nextarc = G.vertices[j].firstarc; G.vertices[j].firstarc = p2; } return OK; } int main() { cout << "採用鄰接表表示法建立無向圖" << endl; ALGraph G; CreatUDG(G); int i; cout << endl; cout << "鄰接表表示法建立的無向圖" << endl; for (i = 0;i < G.vexnum;i++) { VNode temp = G.vertices[i]; ArcNode* p = temp.firstarc; if (p == NULL) { cout << G.vertices[i].data; cout << endl; } else { cout << temp.data; while (p) { cout << "->"; cout << p->adjvex; p = p->nextarc; } } cout << endl; } return 0; }