图的邻接表在 查找 有向图的 出度 很 方便,但是 在 查找 入度 时,需要遍历整个图。如果想要 方便的 查找 入度,需要 建立 逆邻接表。十字链表 正好 就是 邻接表 和 逆邻接表的结合。具体结构图如下:
感觉 十字链表 在 查找 入度时 方便 一些,其他 跟 邻接表没什么区别。
源代码 网盘地址:点击打开链接
代码如下:
// CrossLinkGraph.cpp : 定义控制台应用程序的入口点。
//有向图的十字链表表示法
#include "stdafx.h"
#include <cstdlib>
#define MAX_VEX_NUM 20
enum E_State
{
E_State_Error = 0,
E_State_Ok = 1,
};
struct ArcNode//弧节点
{
int tailIndex;//弧尾位置
int headIndex;//弧头位置
ArcNode * tailNext;//下一个弧尾相同的弧
ArcNode * headNext;//下一个弧头相同的弧
};
typedef struct VNode
{
char vexName;//顶点名称
ArcNode * firstIn;
ArcNode * firstOut;
}GraphList[MAX_VEX_NUM];//
struct Graph
{
GraphList list;//顶点数组.
int vexNum,arcNum;
};
//获取弧 的 头节点
ArcNode * getHeadNode(){
ArcNode * pNode = (ArcNode *)malloc(sizeof(ArcNode));
if (pNode){
pNode->headIndex = pNode->tailIndex = -1;
pNode->headNext = pNode->tailNext = NULL;
}
return pNode;
}
ArcNode * getArcNode(int tailIndex,int headIndex){
ArcNode * pNode = getHeadNode();
if (pNode){
pNode->headIndex = headIndex;
pNode->tailIndex = tailIndex;
}
return pNode;
}
int vexLocation(Graph g,char vex){
for (int i = 0; i < g.vexNum; i++){
if (g.list[i].vexName == vex){
return i;
}
}
return -1;
}
void createGrahp(Graph * g){
printf("输入图的顶点数 和 边(弧)数\n");
scanf("%d%d%*c",&g->vexNum,&g->arcNum);
//构造顶点集
printf("请输入顶点集\n");
for (int i &