#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <malloc.h>
//边节点
typedef struct ArcNode
{
char adjvex;
struct ArcNode* nextarc;
}ArcNode;
//头结点定义
typedef struct VexNode
{
char data;
ArcNode* headnode;
}VexNode;
//图的定义
typedef struct Graph
{
int V;
VexNode* array;
}Graph;
ArcNode* CreateArcNode(char adjvex)
{
ArcNode* arcnode = (ArcNode*)malloc(sizeof(ArcNode));
arcnode->adjvex = adjvex;
arcnode->nextarc = NULL;
return arcnode;
}
Graph* CreateGraph(int V)
{
char s[5] = { 'a','b','c','d','e' };
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->V = V;
graph->array = (VexNode*)malloc(V*sizeof(VexNode));
for (int i = 0; i < V; i++)
{
graph->array[i].data = s[i];
graph->array[i].headnode =NULL;
}
return graph;
}
void Link(Graph* graph, char index, char linked)
{
ArcNode* arc = CreateArcNode(linked);
for (int i = 0; i < graph->V; i++)
{
if (graph->array[i].data == index)
{
arc->nextarc = graph->array[i].headnode;
graph->array[i].headnode = arc;
break;
}
}
}
void print(Graph* graph)
{
for (int i = 0; i < graph->V; i++)
{
printf("%c", graph->array[i].data);
ArcNode* arcdex = graph->array[i].headnode;
while (arcdex)
{
printf("->%c", arcdex->adjvex);
arcdex = arcdex->nextarc;
}
printf("\n");
}
}
int main()
{
Graph* graph = CreateGraph(5);
Link(graph, 'a', 'b');
Link(graph, 'a', 'd');
Link(graph, 'a', 'c');
Link(graph, 'd', 'e');
Link(graph, 'b', 'd');
Link(graph, 'b', 'e');
Link(graph, 'c', 'e');
Link(graph, 'c', 'd');
print(graph);
return 0;
}
邻接表构建有向图代码
最新推荐文章于 2024-08-31 15:34:19 发布