有向图中反向图构造。对tinyDG.txt 文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。
邻接表表示示例如下:
0:1 5
1:
2:0 3
……
代码:
package 算法作业;
import java.io.BufferedReader;
import java.io.FileReader;
class Vertex{
int firstNode;//边的起点
Edge firstEdge;//以firstNode为起点的第一条边
public Vertex(int firstNode){
this.firstNode = firstNode;
firstEdge = null;
}
}
class Edge{
int end;//边的终点
Edge next;//具有同一起点的下一条边
public Edge(int end){
this.end = end;
next = null;
}
}
public class GraphReverse {
int adjListNum;//顶点数目
Vertex adjList[];//正向邻接表顶点数组
Vertex adjListOppsite[];//反向邻接表顶点数组
public GraphReverse(int adjListNum, Vertex adjList[], Vertex adjListOppsite[]) {
this.adjListNum = adjListNum;
this.adjList = adjList;
this.adjListOppsite = adjListOppsite;
}
public static void main(String[] args) {
int verNum;//顶点数与边数
try{
BufferedReader br = new BufferedReader(new FileReader("D:/tinyDG.txt"));
String readStr = br.readLine().trim();//读取第一行
verNum = Integer.parseInt(readStr);
readStr = br.readLine().trim();//读取第二行
//定义两个临时定点表数组(指向正向与反向)
Vertex temporaryVer[] = new Vertex[verNum];
Vertex temporaryVerO[] = new Vertex[verNum];
//正向反向邻接表初始化
for(int i=0;i<temporaryVer.length;i++){
temporaryVer[i] = new Vertex(i);
temporaryVerO[i] = new Vertex(i);
}
readStr = br.readLine().trim();
String str[] = new String[2];
int firstNod,lastNod;
Edge e = null,eO = null;
while(readStr != null){
if(readStr.contains(" ")){
str = readStr.split(" ");
firstNod = Integer.parseInt(str[0]);
lastNod = Integer.parseInt(str[1]);
//正向
e = new Edge(lastNod);
e.next = temporaryVer[firstNod].firstEdge;
temporaryVer[firstNod].firstEdge = e;
//反向
eO = new Edge(firstNod);
eO.next = temporaryVerO[lastNod].firstEdge;
temporaryVerO[lastNod].firstEdge = eO;
}
readStr = br.readLine();
}
GraphReverse graph = new GraphReverse(verNum,temporaryVer,temporaryVerO);
System.out.println("正向图的邻接表:");
for(int i=0;i<temporaryVer.length;i++){
graph.outPut(i);
}
System.out.println("反向图的邻接表:");
for(int i=0;i<temporaryVerO.length;i++){
graph.outPutOppsite(i);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
//输出正向邻接表
public void outPut(int v){
System.out.print(adjList[v].firstNode+": ");
Edge e = adjList[v].firstEdge;
while(e != null){
System.out.print(e.end+" ");
e = e.next;
}
System.out.println();
}
//输出反向邻接表
public void outPutOppsite(int v){
System.out.print(adjListOppsite[v].firstNode+": ");
Edge e = adjListOppsite[v].firstEdge;
while(e != null){
System.out.print(e.end+" ");
e = e.next;
}
System.out.println();
}
}
运行结果: