邻接表构建有向图代码

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值