有向图邻接表,自我感觉比邻接矩阵要理解复杂一点,但是节省的空间不是小数目,所以虽然复杂,但是我们还是要优先考虑邻接表吧。
下面代码简单的写了邻接表,但是基本核心的代码全部包括了,之后图中加权的我也在代码中有所涉及,我们只要更一些参数就可以。基本符合所有要求了吧。
输入:
4 5
a b c d
0 3
1 0
1 2
2 0
2 1
输出:
邻接表
a->3
b->2->0
c->1->0
代码:
#include <iostream>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXVEX 100
/* 最大顶点数,应由用户定义 */
using namespace std;
typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */
typedef char VertexType; /* 顶点类型应由用户定义 */
typedef int EdgeType; /* 边上的权值类型应由用户定义 */
typedef struct EdgeNode /* 边表结点 */
{
int adjvex; /* 邻接点域,存储该顶点对应的下标 */
EdgeType info; /* 用于存储权值,对于非网图可以不需要 */
struct EdgeNode *next; /* 链域,指向下一个邻接点 */
}EdgeNode;
typedef struct VertexNode /* 顶点表结点 */
{
VertexType data; /* 顶点域,存储顶点信息 */
EdgeNode *firstedge;/* 边表头指针 */
}VertexNode, AdjList[MAXVEX];
typedef struct
{
AdjList adjList;
int numNodes,numEdges; /* 图中当前顶点数和边数 */
}GraphAdjList;
/* 建立图的邻接表结构 */
void CreateALGraph(GraphAdjList *G)
{
int i,j,k;
EdgeNode *e;
cout << "输入顶点数和边数:" << endl;
cin >> G->numNodes >> G->numEdges; /* 输入顶点数和边数 */
cout << "读入顶点信息" << endl;
for(i = 0;i < G->numNodes;i++) /* 读入顶点信息,建立顶点表 */
{
cin >> G->adjList[i].data; /* 输入顶点信息 */
G->adjList[i].firstedge=NULL; /* 将边表置为空表 */
}
cout << "输入边(vi,vj)上的顶点序号:" << endl;
for(k = 0;k < G->numEdges;k++)/* 建立边表 */
{
cin >> i >> j; /* 输入边(vi,vj)上的顶点序号 */
e = new EdgeNode; /* 向内存申请空间,生成边表结点 */
e->adjvex = j; /* 邻接序号为j */
e->next=G->adjList[i].firstedge; /* 将e的指针指向当前顶点上指向的结点 */
G->adjList[i].firstedge = e; /* 将当前顶点的指针指向e */
}
}
void PrintfALGraph(GraphAdjList *G)
{
EdgeNode *e;
cout << "邻接表" << endl;
for(int i = 0; i < G->numNodes;i++)
{
e = G->adjList[i].firstedge;
if(e != NULL)
cout << G->adjList[i].data << "->" ;
while(e != NULL)
{
cout << e->adjvex;
e = e->next;
if(e != NULL) cout << "->";
}
cout << endl;
}
}
int main(void)
{
GraphAdjList G;
CreateALGraph(&G);
PrintfALGraph(&G);
return 0;
}