数据结构——图的存储(邻接表)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAX_VERTEX_NUM 20
#define MAX 20
const int error=-1;
const int ok=1;

//表节点
typedef struct ArcNode
{
	int adjvex;   //该弧所指向的顶点的位置
	struct ArcNode *nextarc; //指向下一条弧的指针
}ArcNode;

//头结点
typedef struct VNode
{
	char data[MAX];  //顶点信息
	ArcNode *firstarc;  //指向第一条依附该顶点的弧的指针
}VNode,AdjList[MAX_VERTEX_NUM];

typedef struct
{
	AdjList vertices;
	int vexnum,arcnum; //图的当前顶点数和边数
}ALGraph;

//函数原型:
void CreateAL(ALGraph &G);
int LocatVex(ALGraph G,char v[MAX]);
void haha(ALGraph &G,int w,int z);
void show(ALGraph G);

int main()
{
	ALGraph G;
	CreateAL(G);
	return 0;
}

void CreateAL(ALGraph &G)
{
	int i,x,y;
	char v1[MAX],v2[MAX];
	printf("请输入顶点个数:");
	scanf("%d",&G.vexnum);
	printf("请输入连通的边数:");
	scanf("%d",&G.arcnum);
	for(i=0;i<G.vexnum;i++)
	{
		printf("请输入第%d个顶点的名称: ",i+1);
		scanf("%s",&G.vertices[i].data);
		G.vertices[i].firstarc=NULL;
	}
	for(i=0;i<G.arcnum;i++)
	{
		printf("请输入第一个顶点:");
		scanf("%s",&v1);
		x=LocatVex(G,v1);
		printf("请输入第二个顶点:");
		scanf("%s",&v2);
		y=LocatVex(G,v2);
		haha(G,x,y);
		haha(G,y,x);
	}
	show(G);
}

void haha(ALGraph &G,int w,int z)
{
	ArcNode *p;
	p=(ArcNode*)malloc(sizeof(ArcNode));
	p->adjvex=z;
	p->nextarc=G.vertices[w].firstarc;
	G.vertices[w].firstarc=p;
}

int LocatVex(ALGraph G,char v[MAX])
{
	int i;
	for(i=0;i<G.vexnum;i++)
	{
		if(strcmp(G.vertices[i].data,v)==0)
		{
			return i;
		}
	}
	return error;
}

//显示函数
void show(ALGraph G)
{
	int i;
	ArcNode *p;
	for(i=0;i<G.vexnum;i++)
	{
        p=G.vertices[i].firstarc;
		printf("%s : ",G.vertices[i].data);
		while(p!=NULL)
		{
			printf("%d -> ",p->adjvex);
			p=p->nextarc;
		}
		printf("\n");
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值