#include <stdio.h>
#define MAX_SIZE 100
#define MAX_VERTEX_NUM 20
typedef char Elemtype;
typedef char VertexType;
//边表
struct ArcNode
{
VertexType adjvex;//该弧指向的顶点的值
ArcNode* nextarc;//指向下一条弧的指针
int weight;//权值
};
//顶点表
struct VertexNode
{
VertexType data;//顶点的数据
ArcNode* firstarc;//指向该顶点的第一条弧的指针
};
//逆邻接表结构体
struct AdjList
{
VertexNode Vertex[MAX_VERTEX_NUM];
int vernum, arcnum;
};
//初始化逆邻接表
void InitAdjList(AdjList* G)
{
for (int i = 0; i < G->vernum; i++)
{
G->Vertex[i].data = '#';
G->Vertex[i].firstarc = NULL;
}
}
//输出邻接表或逆邻接表
void show(AdjList G)
{
for (int i = 0; i < G.vernum; i++)
{
ArcNode* p = G.Vertex[i].firstarc;//创建
if (p != NULL)
printf("%c->", G.Vertex[i].data);
else
printf("%c", G.Vertex[i].data);
while (p != NULL)
{
if (p->nextarc != NULL)
{
printf("%c|%d->", p->adjvex, p->weight);
p = p->nextarc;
}
else
{
printf("%c|%d", p->adjvex, p->weight);
p = p->nextarc;
}
}
printf("\n");
}
}
//将邻接表的各个节点链接
void Link_1(AdjList* G, VertexType v1, VertexType v2, int weight)//v1为弧尾,v2为弧头
{
ArcNode* s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = v2;
s->weight = weight;
s->nextarc = NULL;
for (int i = 0; i < G->vernum; i++)
{
//判断领接表的顶点表的firstarc指针域是否为空,如果是空的,那么直接在其后插入,否则进行头插法建表
if (G->Vertex[i].data == v1 && G->Vertex[i].firstarc == NULL)
{
G->Vertex[i].firstarc = s;
}
else
if (G->Vertex[i].data == v1 && G->Vertex[i].firstarc != NULL)
{
//头插法建立邻接表
s->nextarc = G->Vertex[i].firstarc;
G->Vertex[i].firstarc = s;
}
else continue;
}
}
//将逆邻接表的各个节点链接
void Link_2(AdjList* G, VertexType v1, VertexType v2, int weight)//v1为弧尾,v2为弧头
{
ArcNode* s = (ArcNode*)malloc(sizeof(ArcNode));
s->adjvex = v1;
s->weight = weight;
s->nextarc = NULL;
for (int i = 0; i < G->vernum; i++)
{
//判断领接表的顶点表的firstarc指针域是否为空,如果是空的,那么直接在其后插入,否则进行头插法建表
if (G->Vertex[i].data == v2 && G->Vertex[i].firstarc == NULL)
{
G->Vertex[i].firstarc = s;
}
else
if (G->Vertex[i].data == v2 && G->Vertex[i].firstarc != NULL)
{
//头插法建立邻接表
s->nextarc = G->Vertex[i].firstarc;
G->Vertex[i].firstarc = s;
}
else continue;
}
}
//创建邻接表
void Creat(AdjList* G,AdjList *M)
{
int weight;
VertexType v1, v2;
printf("请输入顶点数和弧数:");
scanf("%d %d", &G->vernum, &G->arcnum);
InitAdjList(G);
printf("请输入各顶点:");
for (int i = 0; i < G->vernum; i++)
scanf(" %c", &G->Vertex[i].data);
M = G;
for (int i = 0; i < G->arcnum; i++)
{
printf("输入一条弧的两个顶点和权值:");
scanf(" %c %c %d", &v1, &v2, &weight);
Link_2(M, v1, v2, weight);//链接邻接表
Link_1(G, v1, v2, weight);//链接逆邻接表
}
}
int main()
{
AdjList G, M;
printf("请创建邻接表\n");
Creat(&G,&M);
printf("该图的邻接表为:\n");
show(G);
printf("该图的逆邻接表为:\n");
show(M);
//TopoSort(M, G);
}
运行结果及报错内容
无法创建我所需要的邻接表
我的解答思路和尝试过的方法
我想要达到的结果
我希望能够输入一组数据,创建它的邻接表和逆邻接表