以al存储结构为邻接表的方式创建图;

#include<stdio.h>
#include<stdlib.h>
#define MAX_VERTEX_NUM 100

typedef struct Arcnode {
	int adjvex; //该边的另一个顶点位置
	struct Arcnode* nextarc;//指向下一条边
}Arcnode;

typedef struct vnode {
	int data;//顶点的值
	Arcnode *firstarc;//指向第一条依附于该顶点边的指针
}vnode,adjlist[MAX_VERTEX_NUM];

typedef struct {
	adjlist vertices;//顶点数组
	int vexnum, arcnum;
}Graph;


 int locatevex(Graph G, int v) 
{//定位函数
	for (int i = 0; i < G.vexnum; i++) 
	{
		if (v == G.vertices[i].data)return i;

	}

}

void CreateGraph(Graph& G)
{
	Arcnode* p, * q;
	int i,j,k, v1,v2;
	printf("分别输入顶点个数和边的数目: \n");
	scanf_s(" %d%d", &G.vexnum, &G.arcnum);
	printf("分别输入各个顶点值: \n");
	for (i = 0; i < G.vexnum; i++)
	{
		scanf_s("%d",&G.vertices[i].data);
		G.vertices[i].firstarc = NULL;//初始化
	}
	printf("分别输入各条边的两个顶点: \n");
	for(k = 0; k < G.arcnum; k++)
	{
		scanf_s("%d%d", &v1, &v2);
		
		i = locatevex(G,v1); j = locatevex(G, v2);//定位
		p = (Arcnode*)malloc(sizeof(Arcnode));//申请-一个结点
		p->adjvex = j; p->nextarc = NULL;//赋值
		p->nextarc = G.vertices[i].firstarc;//连接结点
		G.vertices[i].firstarc = p;//连接结点
		q = (Arcnode*)malloc(sizeof(Arcnode));
		q->adjvex = i; q->nextarc = NULL;
		q->nextarc = G.vertices[j].firstarc; 
		G.vertices[j].firstarc = q;
	}
}
int main(void)
{
	Graph G;
	CreateGraph(G);


	return 0;
}
上一篇 下一篇