有向图的邻接表
#include <iostream>
using namespace std;
#define MVnum 100
typedef string VertexType;
typedef struct ArcNode
{
int adjvex;
struct ArcNode* nextarc;
int weight;
}ArcNode;
typedef struct VNode
{
VertexType data;
struct ArcNode* firstarc;
}VNode, VNodeList[MVnum];
typedef struct
{
VNodeList vertices;
int vexnum;
int edgenum;
}Graph;
int locatevex(Graph G, VertexType v)
{
for (int i = 0; i < G.vexnum; i++)
{
if (G.vertices[i].data == v) return i;
}
return -1;
}
void CreateDG(Graph& G)
{
int i = 0, j = 0;
int k = 0;
cout << "请输入总顶点数和总边数:";
cin >> G.vexnum >> G.edgenum;
cout << "输入顶点:";
for (i = 0; i < G.vexnum; i++)
{
cin >> G.vertices[i].data;
G.vertices[i].firstarc = NULL;
}
for (int k = 0; k < G.edgenum; k++)
{
VertexType v1, v2;
cout << "输入第" << k + 1 << "条边:";
cin >> v1 >> v2;
i = locatevex(G, v1);
j = locatevex(G, v2);
ArcNode* p1 = (ArcNode*)malloc(sizeof(ArcNode));
if (p1 == NULL)
{
cout << "内存分配失败" << endl;
exit(0);
}
p1->adjvex = j;
p1->nextarc = G.vertices[i].firstarc;
G.vertices[i].firstarc = p1;
}
}
/*--------将邻接表输出在控制台上---------*/
void PrintfUGraph(Graph G) {
for (int i = 0; i < G.vexnum; i++)
{
cout << G.vertices[i].data << ":";
ArcNode* p = (ArcNode*)malloc(sizeof(ArcNode));
p = G.vertices[i].firstarc;
while (p != NULL)
{
cout << p->adjvex << " ";
p = p->nextarc;
}
cout << endl;
}
}
/*
5 6
v1 v2 v3 v4 v5
v1 v2
v1 v4
v3 v4
v2 v3
v3 v5
v2 v5
*/
int main(void)
{
Graph G;
CreateDG(G);
PrintfUGraph(G);
return 0;
}