#include<iostream>
using namespace std;
#define MVNum 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* firststarc; // 指向第一条边依附顶点的边的指针
}VNode, AdjList[MVNum]; // AdjList表示邻接表类型
typedef struct {
AdjList vertices; // 邻接表
int vexnum, arcnum;
}ALGraph;
int LocateUDG(ALGraph G, VerTexType v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (G.vertices[i].data == v)
{
return i;
}
}
return -1;
}
int CreateUDG(ALGraph& G)
{
cout << "请输入总顶点数,总边数:";
cin >> G.vexnum >> G.arcnum;
cout << endl;
cout << "输入点的名称: " << endl;
for (int i = 0; i < G.vexnum; i++)
{
cout << "请输入第" << i + 1 << "个点的名称:";
cin >> G.vertices[i].data;
G.vertices[i].firststarc = NULL;
}
cout << endl;
cout << "请输入一条边依附的顶点:" << endl;
for (int k = 0; k < G.arcnum; k++)
{
VerTexType v1, v2;
cout << "请输入第" << k + 1 << "条依附的两个顶点:";
cin >> v1 >> v2;
int i = LocateUDG(G, v1);
int j = LocateUDG(G, v2);
ArcNode* p1 = new ArcNode;
p1->adjvex = j;
p1->nextarc = G.vertices[i].firststarc;
G.vertices[i].firststarc = p1;
ArcNode* p2 = new ArcNode;
p2->adjvex = i;
p2->nextarc = G.vertices[i].firststarc;
G.vertices[j].firststarc = p2;
}
return OK;
}
int main()
{
cout << "邻接表创建无向图" << endl;
ALGraph G;
CreateUDG(G);
for (int i = 0; i < G.vexnum; i++)
{
VNode temp = G.vertices[i];
ArcNode* p = temp.firststarc;
if (!p)
{
cout << G.vertices[i].data << endl;
}
else
{
cout << temp.data;
while (p)
{
cout << "->" << p->adjvex;
p = p->nextarc;
}
}
cout << endl;
}
return 0;
}
06-27
7157
12-10
1197