开始攻克图的算法,先从最简单的存储开始实现,本文关于邻接表的实现。
邻接表是图的存储中最简单也是最基本的存储结构,基于链表的思想实现的。在邻接表中,对于中的每个顶点建立一个单链表,第i个单链表中的节点表示依附于顶点的vi的边。每个节点由3个域组成其中邻接点域(adjvex)指示与顶点vi邻接的点在图中的位置,链域(nextarc)指示下一条边或弧的节点;数据域(info)存储和边或弧相关的信息,如权值等,每个链表上附设一个表头节点。在表头节点中除了设有链域(firstarc)指向链表中的第一个节点之外,还设有存储顶点vi的名或其他有关信息的数据域(data)。
两种表结构如图:
我以下面的图结构为例进行操作:
下面把代码贡献出来:
Adj_List.h
#ifndef __ADJ_LIST_H__
#define __ADJ_LIST_H__
#define MAX_VERTEX_NUM 20
typedef struct ArcNode
{
char adjvex;
struct ArcNode *nextarc;
int *info;
}ArcNode;
typedef struct VNode
{
char data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct ALGraph
{
AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;
#endif /* __ADJ_LIST_H__*/
graph_storage.c
/*
************************************************
*Name : graph_storage.c *
*Date : 2015-05-27 *
*Author : sniper *
*Aim : It will storage the graph using the adj-*
* acency list,and travel the pragh. *
************************************************
*/
#include <stdio.h>
#include <stdlib.h>
#include "Adj_list.h"
int create(ALGraph *G)
{
int i,j;
int node_pair1,node_pair2;
ArcNode *arc;
node_pair1=0;
node_pair2=0;
i=0;
j=0;
printf("please input the number of node and edge: ");
scanf("%d %d",&G->vexnum,&G->arcnum);
for(i=0;i<G->vexnum;i++)
{
G->vertices[i].data = 'A'+i;
G->vertices[i].firstarc = NULL;
}
printf("finish the Node!\n");
for(j=0;j<G->arcnum;j++)
{
printf("please input the node pair: ");
scanf("%d %d",&node_pair1,&node_pair2);
node_pair1-=1;
node_pair2-=1;
/*
*Node pair get match with each other
*and storage into the adjacency list.
*/
arc = (ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex = node_pair2+'A';
arc->nextarc=G->vertices[node_pair1].firstarc;
G->vertices[node_pair1].firstarc=arc;
arc = (ArcNode *)malloc(sizeof(ArcNode));
arc->adjvex = node_pair1+'A';
arc->nextarc=G->vertices[node_pair2].firstarc;
G->vertices[node_pair2].firstarc=arc;
}
printf("finish the Adjacency List\n");
return 0;
}
int main()
{
ALGraph *G;
int i;
i=0;
G = (ALGraph *)malloc(sizeof(ALGraph));
create(G);
/*
*print the adjacency list
*/
for(i=0;i<G->vexnum;i++)
{
printf("%c -> ",'A'+i);
while(G->vertices[i].firstarc!=NULL)
{
printf("%c -> ",G->vertices[i].firstarc->adjvex);
G->vertices[i].firstarc=G->vertices[i].firstarc->nextarc;
}
printf("\n");
}
return 0;
}
也可以从我的GitHub clone
https://github.com/cremyos/Graph_Adj_List
测试用例:
5 6
1 2
1 4
2 3
2 5
3 4
3 5
好了下次该解决下面的问题了!