这篇文章将为大家详细讲解有关用图的邻接表法创建图的实现完整C代码怎么写,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
/* 无向图的邻接表法创建图的C代码实现 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MaxSize 20 //图顶点的最大数量
typedef char VertexType;
//全局变量,记录图的结点的数量
int VertexNum;
//定义图顶点
typedef struct GraphNode {
VertexType ver;
struct GraphNode *next;
}GraphNode;
//用邻接表法创建图
void CreateGraph( GraphNode **g )
{
VertexType ch; //用来接收顶点名称
int i = 0;
GraphNode *p, *q;
(*g) = (GraphNode *)malloc(sizeof(GraphNode)*MaxSize);//分配一个结构体数组
printf("请输入图的顶点:\n"); //存储图的顶点
scanf("%c", &ch);
while( '\n' != ch ) {
(*g)[i].ver = ch;
(*g)[i].next = NULL;
i++;
scanf("%c", &ch);
}
VertexNum = i; //记录顶点数
for( i=0; i<VertexNum; i++ ) { //存储图的边信息
q = (*g)+i;
printf("请输入顶点 %c 的邻接顶点:\n", q->ver );
scanf("%c", &ch);
while( '\n' != ch ) {
p = (GraphNode *)malloc(sizeof(GraphNode));
p->ver = ch;
q->next = p;
q = p;
q->next = NULL;
scanf("%c", &ch);
}
}
}
//打印邻接表法创建的图
void PrintGraph( GraphNode *g )
{
GraphNode *p;
printf("图的顶点为:\n"); //打印顶点
for( int i=0; i<VertexNum; i++ )
printf("%c ", g[i].ver);
printf("\n");
printf("图的顶点以及其对应的邻接顶点为:\n"); //打印邻接点
for( i=0; i<VertexNum; i++ ) {
printf("%c :", g[i].ver);
p = g[i].next;
while( NULL != p ) {
printf("%c ", p->ver);
p = p->next;
}
printf("\n");
}
}
int main()
{
GraphNode *g;
CreateGraph( &g );
PrintGraph( g );
return 0;
}
测试的图:
测试结果
关于用图的邻接表法创建图的实现完整C代码怎么写就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.xuebuyuan.com/3261897.html