1. 结构体定义
typedef struct ArcNode {
int adjVex;
struct ArcNode *next;
};
typedef struct {
char name;
struct ArcNode *first;
}VexNode, *VexList;
typedef struct {
VexList vexs;
int vexNum, arcNum;
}AdjListGraph;
2. 初始化
void AdjListGraphInit(AdjListGraph *ag, int vexNum, char *vexs)
{
ag->vexNum = vexNum;
ag->arcNum = 0;
ag->vexs = malloc(sizeof(VexNode) * vexNum);
for(int i = 0;i < vexNum;i++){
ag->vexs[i].name = vexs[i];
ag->vexs[i].first = NULL;
}
}
3. 定位结点的位置
int AdjListGraphLocateVex(AdjListGraph *ag, char vex)
{
for(int i = 0;i < ag->vexNum;i++)
if(ag->vexs[i].name == vex)
return i;
return -1;
}
4. 查找第一个邻接点
char AdjListGraphFirstAdjVex(AdjListGraph *ag, char vex)
{
int vexNo = AdjListGraphLocateVex(ag, vex);
if(vexNo < 0)
return '\0';
ArcNode *first = ag->vexs[vexNo].first;
if(first == NULL)
return '\0';
return ag->vexs[first->adjVex].name;
}
5. 查找下一个邻接点
char AdjListGraphNextAdjVex(AdjListGraph *ag, char vex, char pre)
{
int vexNo = AdjListGraphLocateVex(ag, vex);
int start = AdjListGraphLocateVex(ag, pre);
if(vexNo < 0 || start < 0)
return '\0';
ArcNode *arc = ag->vexs[vexNo].first;
while(arc != NULL){
if(arc->adjVex == start)
break;
arc = arc->next;
}
if(arc == NULL)
return '\0';
arc = arc->next;
return arc == NULL ? '\0' : ag->vexs[arc->adjVex].name;
}
6. 插入弧
void AdjListGraphInserArc(AdjListGraph *ag, char vex1, char vex2)
{
int vexNo1 = AdjListGraphLocateVex(ag, vex1);
int vexNo2 = AdjListGraphLocateVex(ag, vex2);
if(vexNo1 < 0 || vexNo2 < 0)
return;
ArcNode *arc1 = malloc(sizeof(ArcNode));
ArcNode *arc2 = malloc(sizeof(ArcNode));
arc1->adjVex = vexNo2;
arc2->adjVex = vexNo1;
arc1->next = ag->vexs[vexNo1].first;
ag->vexs[vexNo1].first = arc1;
arc2->next = ag->vexs[vexNo2].first;
ag->vexs[vexNo2].first = arc2;
ag->arcNum++;
}