1、邻接矩阵
图的邻接矩阵存储也称数组表示法,其方法是用一个一维数组存储图中顶点的信息,用一个二维数组存储图中边的信息(即各顶点之间的邻接关系),存储顶点之间邻接关系的二维数组称为邻接矩阵。
</pre>无向图的邻接矩阵表示:<pre name="code" class="cpp">template<class T>
class MGraph
{
public:
MGraph(T a[],int n,int e);
~MGraph(){};
private:
T vertex[10];
int arc[10][10];
int vertexNum,arcNum;
}
template<class T>
void MGraph::MGraph(T a[],int n,int e)
{
vertexNum=n;
arcNum=e;
for(int i=0;i<vertexNum;i++)
{
vertex[i]=a[i];
}
for(int i=0;i<vertexNum;i++)
for(int j=0;j<vertexNum;j++)
arc[i][j]=0;
int x,y;
for(int k=0;k<arcNum;k++)
{
cin>>x>>y;
arc[x][y]=1;
}
}
2、邻接表
对于图的每个顶点V
i,将所有邻接于的顶点V
i链成一个单链表,称为顶点V
i的边表。为了方便对所有边表的头指针进行存取操作,可以采取顺序存储。存储边表头指针的数组和存储顶点信息的数组构成了邻接表的表头数组,称为顶点表。所以,在邻接表中存在两种节点结构:顶点表节点和边表节点。
无向图的邻接表表示:
struct ArcNode //定义边表节点
{
int adjvex;
ArcNode* next;
};
template<class T>
struct VertxNode //定义顶点表节点
{
T vertex;
ArcNode* firstedge;
};
template<class T>
class ALGraph
{
public:
ALGraph(T a[],int n,int e);
~ALGraph;
private:
VertxNode adjlist[10];
int vertexNum,arcNum;
}
template<class T>
ALGraph::ALGraph(T a[],int n,int e)
{
vertexNum=n;
arcNum=e;
for(int i=0;i<vertexNum;i++)
{
adjlist[i].vertex=a[i];
adjlist[i].firstedge=NULL;
}
int x,y;
for(int k=0;k<arcNum;k++)
{
cin>>x>>y; //输入边所依附的两个顶点的编号
ArcNode* s=new ArcNode; //生成一个边表节点s
s->adjvex=y;
s->next=adjlist[x].firstedge;
adjlist[x].firstedge=s; //将节点s插入到第x边表的表头
}
}