您的位置:首页 > 其它

第五周作业——有向图邻接表表示及反向图构造

2014-06-08 14:49 435 查看
package homework;
import java.io.*;

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,arNum;//顶点数与边数
try{
FileReader f = new FileReader("C:\\Users\\orion\\Desktop\\tinyG.txt");
BufferedReader br = new BufferedReader(f);

String readStr = br.readLine().trim();//读取第一行
verNum = Integer.parseInt(readStr);
readStr = br.readLine().trim();//读取第二行
arNum = Integer.parseInt(readStr);

//定义两个临时定点表数组(指向正向与反向)
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();
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: