【注】参考《妙趣横生的算法》实现
//图的建立
#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();
}