图的创建

【注】参考《妙趣横生的算法》实现

//图的建立
#include <stdio.h>
#include <malloc.h>
#define MAX_VERTEX_NUM 20

typedef struct ArcNode{
	int data;
	struct ArcNode * next;
	int *weight;
}ArcNode;

typedef struct VNode{
	int data;
	struct ArcNode *firstarc;
}VNode;

//创建图的函数
void CreateGraph(int n, VNode G[]){
	int i, temp;
	ArcNode *arcptr1 = NULL, *arcptr2 = NULL;

	//首先得到每个顶点的值,并且将顶点的边置为NULL
	printf("输入图中的顶点的值:\n");
	for(i = 0; i < n; i++){
		scanf("%d", &G[i].data);
		G[i].firstarc = NULL;
	}

	//为每一个顶点设置边
	for(i = 0; i < n; i++){
		printf("请输入%d点的边(输入-1结束):\n", i);
		scanf("%d", &temp);
		while(temp != -1){//创建边,分配内存空间
			arcptr1 = (ArcNode*)malloc(sizeof(ArcNode));//arcptr1指向新分配的边
			(*arcptr1).next = NULL;
			if(G[i].firstarc == NULL){//给顶点找第一条边
				G[i].firstarc = arcptr1;
			}else{
				(*arcptr2).next = arcptr1;
			}			
			arcptr2 = arcptr1;//让arcptr2始终指向最后分配的边
			scanf("%d", &temp);
		}
	}
}

void main(){
	VNode G[3];
	CreateGraph(3, G);
	getchar();
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值