图有多种存储方式,这里仅介绍较为常用的邻接表存储。
源代码如下:
#include "stdio.h"
#include "malloc.h"
typedef struct Node //边表结点结构体定义
{
int adjvex;
struct Node *next;
} Node, *ANode;
typedef struct //顶点表结点结构体定义
{
int data;
ANode first;
}VNode, Adjlist[30];
typedef struct graph //图结构体定义
{
Adjlist adjlist;
int n, e;
}graph, *ALGraph;
void create(ALGraph &G); //图的创建
void AList(ALGraph G); //图的邻接表表示
int main()
{
ALGraph G;
create(G);
AList(G);
return 0;
}
//图的邻接表存储
void create(ALGraph &G)
{
int v, k, flag = 0;
ANode p;
G = (ALGraph)malloc(sizeof(graph));
printf("请输入顶点数和边数:\n");
scanf("%d %d", &G->n, &G->e);
for(v = 1; v <= G->n; ++v)
{
G->adjlist[v-1].data = v;
G->adjlist[v-1].first = NULL;
printf("请输入顶点%d的第一个邻接点:", v);
scanf("%d", &k);
while(k != 0)
{
if(flag == 0)
{
G->adjlist[v-1].first = (ANode)malloc(sizeof(Node));
G->adjlist[v-1].first->adjvex = k;
G->adjlist[v-1].first->next = NULL;
p = G->adjlist[v-1].first;
}
else
{
ANode q = (ANode)malloc(sizeof(Node));
q->adjvex = k;
q->next = NULL;
p->next = q;
p = q;
}
++flag;
printf("请输入该顶点的下一个邻接点:");
scanf("%d", &k);
}
flag = 0;
printf("\n");
}
}
void AList(ALGraph G)
{
int v;
printf("该图的邻接表表示:\n");
for(v = 0; v < G->n; ++v)
{
printf("%d→", v);
while(G->adjlist[v-1].first != NULL)
{
printf("%d→", G->adjlist[v-1].first->adjvex);
G->adjlist[v-1].first = G->adjlist[v-1].first->next;
}
printf("NULL\n");
}
}
示例:(读者可自行验证)