现在的位置: 首页 > 编程语言 > 正文

用图的邻接表法创建图的完整C代码实现

2019年04月25日 编程语言 ⁄ 共 1078字 ⁄ 字号 评论关闭
/* 无向图的邻接表法创建图的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;
}

测试的图:

测试结果

抱歉!评论已关闭.