如题;这是一套完整的可运行的代码;需要读者有一定的基础去阅读;
语言是用C语言实现;在C++环境中编写;在C++中可直接运行;在C语言中需要改部分头文件和输出语句;
头文件;这要是代码的声明部分;
# ifndef _AMLGRAPH_
# define _AMLGRAPH_
# include <iostream>
using namespace std;
# define MaxVertexNum 256
typedef enum
{
unvisited, visited
}VisiteIf;
typedef int InfoType;
typedef char VertexType;
typedef struct EdgeNode
{
VisiteIf mark;
int ivertex;
struct EdgeNode * ilink;
int jvertex;
struct EdgeNode * jlink;
InfoType info;
}EdgeNode;
typedef struct VertexNode
{
VertexType vertex;
EdgeNode * firstedge;
}VertexNode;
typedef struct
{
VertexNode adjmulist[MaxVertexNum];
int vertexNum;
int edgeNum;
}AMLGraph, * PAMLGraph;
PAMLGraph CreateGraph(void);
# endif
实现文件;主要是代码的实现;
# include "AMLGraph.h"
PAMLGraph CreateGraph(void)
{
PAMLGraph g = (PAMLGraph)malloc(sizeof(AMLGraph));
if (NULL != g)
{
memset(g, 0, sizeof(AMLGraph));
g->vertexNum = 0;
g->edgeNum = 0;
//输入定点数和边数;
cout << "Please input VertexNum and EdgeNum: " << endl;
cin >> g->vertexNum >> g->edgeNum;
//初始化顶点表;
for (int i = 0; i < g->vertexNum; i++)
{
cout << "Please input element value: " << endl;
cin >> g->adjmulist[i].vertex;
g->adjmulist[i].firstedge = NULL;
}
//初始化边表;
int i = 0;
int j = 0;
EdgeNode * p = NULL;
for (int k = 0; k < g->edgeNum; k++)//乘2是为了保证相同的边起始端点不容可以输入;
{
//输入边的两个端点;
cout << "Please input edge two index; " << endl;
cin >> i >> j;
//连接边节点;
p = (EdgeNode *)malloc(sizeof(EdgeNode));
p->mark = unvisited;
p->ivertex = i;
p->ilink = g->adjmulist[i].firstedge;
g->adjmulist[i].firstedge = p;
p->jvertex = j;
p->jlink = g->adjmulist[j].firstedge;
g->adjmulist[j].firstedge = p;
p->info = 0;
}
return g;
}
else
{
cout << "Memory allocate error! " << endl;
system("pause");
exit(0);
}
}
Main函数;
# include "AMLGraph.h"
int main(int argc, char ** argv)
{
PAMLGraph g = CreateGraph();
cout << g->adjmulist[0].firstedge->ivertex << endl;
cout << g->adjmulist[0].firstedge->jvertex << endl;
cout << g->adjmulist[0].firstedge->ilink->ivertex << endl;
cout << g->adjmulist[0].firstedge->ilink->jvertex << endl;
if (NULL != g->adjmulist[1].firstedge->jlink)
{
cout << g->adjmulist[1].firstedge->ivertex << endl;
cout << g->adjmulist[1].firstedge->jlink->jvertex << endl;
}
if (NULL != g->adjmulist[2].firstedge->jlink)
{
cout << g->adjmulist[2].firstedge->jlink->jvertex << endl;
cout << g->adjmulist[2].firstedge->jlink->ivertex << endl;
}
cout << g->adjmulist[2].firstedge->ivertex << endl;
cout << g->adjmulist[2].firstedge->jvertex << endl;
cout << g->adjmulist[2].firstedge->ilink->ivertex << endl;
cout << g->adjmulist[2].firstedge->ilink->jvertex << endl;
cout << g->adjmulist[2].firstedge->ilink->ilink->ivertex << endl;
cout << g->adjmulist[2].firstedge->ilink->ilink->jvertex << endl;
cout << g->adjmulist[4].firstedge->ivertex << endl;
cout << g->adjmulist[4].firstedge->jvertex << endl;
system("pause");
return 0;
}