上次学习了图的邻接表,对于有向图来讲,邻接表是有缺陷的,我们想得到一个顶点的出度,对该顶点的边表遍历即可,需要一个顶点的入度,则需要遍历整个图(逆邻接表解决了入度,解决不了出度)。
这时可以将邻接表跟逆邻接表结合起来就是我们所要说的——十字链表。
这里是个小例子:
图1
内部类定义顶点数组:三个属性分别存放顶点,入边表,出边表
private class VertexeType {
String vertexe = null;
AdjacencyType fristin = null;// 入边表(顶点为弧尾)
AdjacencyType fristout = null;// 出边表(顶点为弧头)
//这里省略get,set及构造方法
}
内部类定义边表邻接点:
private class AdjacencyType {
int verNum = -1;// 弧的起点在顶点数组中的下标
int headVex = -1;// 弧终点在顶点数组中的下标
AdjacencyType headLink = null;// 指向下一个终点相同的邻接点
AdjacencyType adjLink = null;// 指向下一个起点相同的邻接点
//这里省略get,set及构造方法
}
通过二维数组添加所有邻接点:
public void addAdj(String[][] strArr) {
for (int i = 0; i < strArr.length; i++) {
AdjacencyType temp = null;
AdjacencyType tempin = null;
int posOne = getPosition(strArr[i][0]);//获取弧尾在顶点数组中的下标
int posTwo = getPosition(strArr[i][1]);//获取弧头在顶点数组中的下标
AdjacencyType adj = new AdjacencyType();
adj.setVerNum(posOne);
adj.setHeadVex(posTwo);
temp = this.verArr[posOne].getFristout();
tempin = this.verArr[posTwo].getFristin();
if (temp == null) {
this.verArr[posOne].setFristout(adj);
} else {
while (true) {
if (temp.getAdjLink() != null) {
temp = temp.getAdjLink();
} else {
temp.setAdjLink(adj);
break;
}
}
}
if (tempin == null) {
this.verArr[posTwo]