//采用邻接表表示法创建无向图
#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;
}