十字链表存储有向图

一、算法基本思想

从上图中选出3个结点分析运行过程

1.第一次循环

 2.第二次循环

 3.第三次循环

二、代码如下

/*
项目名称:十字链表存储有向图
编译环境:VC++ 2008
作者相关:。。。
最后修改:2019.10.29
学习目标:1.掌握十字链表存储图的基本操作
注意事项:1.测试所有功能是否正常

遇到问题:

*/

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

#define MAX_VERTEX_NUM 20
#define OK    1
#define ERROR 0

typedef char VertexType;
typedef char InfoType;
typedef bool Status;

typedef struct ArcNode
{
	int tailvex,headvex;//该弧的尾和头顶点的下标
	struct ArcNode *hlink,*tlink;//hlink为入边表指针域,指向终点相同的下一条边
	InfoType *info;//该弧相关信息的指针
}ArcNode;

typedef struct VexNode
{
	VertexType data;
	ArcNode *firstin,*firstout;//分别指向入边表和处边表的第一个结点
}VexNode;

typedef struct
{
	VexNode vexs[MAX_VERTEX_NUM];//顶点数组
	int vexnum,arcnum;
}OLGraph;

Status CreateDG(OLGraph &G);

int LocateVex(OLGraph G,VertexType v);

int main()
{
	OLGraph G;
	CreateDG(G);

	return 0;
}
//十字链表存储有向图
Status CreateDG(OLGraph &G)
{
	int IncInfo,i,j,k;
	VertexType v1,v2;
	ArcNode *p;

	printf("请输入图的顶点数、弧数以及弧是否含有信息(0否1是)\n");
	fflush(stdin);
	scanf("%d%d%d",&G.vexnum,&G.arcnum,&IncInfo);

	for(i=0;i<G.vexnum;i++)
	{
		printf("请输入第%d个顶点: ",i+1);
		fflush(stdin);
		scanf("%c",&G.vexs[i].data);
		G.vexs[i].firstin=NULL;
		G.vexs[i].firstout=NULL;
	}

	for(k=0;k<G.arcnum;k++)//构造十字链表
	{
		printf("请输入第%d条弧的起点和终点\n",k+1);
		fflush(stdin);
		scanf("%c,%c",&v1,&v2);

		i=LocateVex(G,v1);
		j=LocateVex(G,v2);

		p=(ArcNode *)malloc(sizeof(ArcNode));
		p->tailvex=i;//弧起点在顶点表的下标
		p->headvex=j;//弧终点在顶点表的下标
		p->hlink=G.vexs[j].firstin;
		p->tlink=G.vexs[i].firstout;
		G.vexs[j].firstin=G.vexs[i].firstout=p;//头插法,无关顺序
	}

	return OK;
}
//确定顶点v的下标
int LocateVex(OLGraph G,VertexType v)
{
	int index;
	for(index=0;index<G.vexnum;index++)
		if(G.vexs[index].data==v)
			return index;
	if(index==G.vexnum)
		return -1;
}
发布了62 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Sruggle/article/details/102809130