邻接矩阵表示法:(将图映射到二维数组)
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define Overflow 2//上溢
#define Underflow 3//下溢
#define NotPresent 4//元素不存在
#define Duplicate 5//有重复元素
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType **a; //邻接矩阵
int n;//图的当前顶点数
int e;//图的当前边数
ElemType noEdge;//两顶点间无边时的值
}mGraph;
Status Init(mGraph *mg,int nSize,ElemType noEdgeValue)//初始化邻接矩阵 nSize为初始化矩阵的一行元素个数
{
int i,j;
mg->n = nSize;
mg->e = 0;
mg->noEdge=noEdgeValue;
mg->a=(ElemType**)malloc(nSize*sizeof(ElemType*));//以矩阵一行为单位的一维数组(实质是一维指针数组)
if(!mg->a)
return ERROR;
for(i = 0;i < mg->n ;i++)
{
mg->a[i] = (ElemType*)malloc(nSize*sizeof(ElemType));//为一维指针数组实例化(为一行中的每个整型元素实例化)
for (j = 0;j < mg->n ; j++)
mg->a[i][j]=mg->noEdge;//为每个元素赋值
mg->a[i][i]=0;//将代表从顶点到自身的点初始化为0
}
return OK;
}
void Destroy (mGraph *mg)//邻接矩阵的释放
{
int i;
for(i = 0;i<mg->n;i++)
free(mg->a[i]);
free(mg->a);
}
Status Exitst (mGraph *mg,int u,int v)//边的搜索
{
if(u<0||v<0||u>mg->n-1||v>mg->n-1||u==v||mg->a[u][v]==mg->noEdge)
return ERROR;
return OK;
}
Status Insert(mGraph *mg,int u,int v,ElemType w)//边的插入
{
if(u<0||v<0||u>mg->n-1||v>mg->n-1||u==v)
return ERROR;
if(mg->a[u][v]!=mg->noEdge)
return Duplicate;
mg->a[u][v]=w;
mg->e++;
return OK;
}
Status Remove(mGraph *mg,int u,int v)//边的删除
{
if(u<0||v<0||u>mg->n-1||v>mg->n-1||u==v)
return ERROR;
if(mg->a[u][v]!=mg->noEdge)
return NotPresent;
mg->a[u][v]=mg->noEdge;
mg->e--;
return OK;
}
邻接表表示法:(将图映射到链表)
typedef struct ENode
{
int adjVex;//任意顶点u的相邻顶点
ElemType w;//边的权值
struct ENode* nextArc;
}ENode;
typedef struct
{
int n;
int e;
ENode **a;
}LGraph;
Status Init(LGraph *lg,int nSize)//初始化
{
int i;
lg->n=nSize;
lg->a=(ENode**)malloc(nSize*sizeof(ENode*));//生成一维指针数组
if(!lg->a)
return OK;
else
{
for(i=0;i<lg->n;i++)
lg->a[i]=NULL;//将指针数组初始化
return OK;
}
}
void Destroy(LGraph *lg)//释放邻接表
{
int i;
ENode *p,*q;
for(i=0;i<lg->n;i++)
{
p=lg->a[i];
q=p;
while(p)
{
p=p->nextArc;
free(q);
q=p;
}
}
free(lg->a);
}
Status Exitst (LGraph *lg,int u,int v)//边的搜索
{
ENode* p;
if(u<0||v<0||u>lg->n-1||v>lg->n-1||u==v)
return ERROR;
p=lg->a[u];
while(p&&p->adjVex!=v)
p=p->nextArc;
if(!p)
return ERROR;
else
return OK;
}
Status Insert (LGraph *lg,int u,int v,ElemType w)
{
ENode *p;
if(u<0||v<0||u>lg->n-1||v>lg->n-1||u==v)
return ERROR;
if(Exit(lg,u,v))
return Duplicate;
p=(ENode*)malloc(sizeof(ENode));
p->adjVex=v;
p->w=w;
p->nextArc=lg->a[u];
lg->a[u]=p;
lg->e++;
return OK;
}
Status Remove(LGraph *lg,int u,int v)//边的删除
{
ENode *p,*q;
if(u<0||v<0||u>lg->n-1||v>lg->n-1||u==v)
return ERROR;
p=lg->a[u],q=NULL;
while(p&&p->adjVex!=v)
{
q=p;
p=p->nextArc;
}
if(!p)
return NotPresent;
if(q)
q->nextArc=p->nextArc;
else
lg->a[u]=p->nextArc;
free(p);
lg->e--;
return OK;
}