1. 有向图中反向图构造。对tinyDG.txt(http://pan.baidu.com/s/1o6jWtcA)文件所表示的图,输出其邻接表表示 与 反向图的邻接表表示。类名:GraphReverse。
邻接表表示示例如下:
0:1 5
1:
2:0 3
……
代码实现
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
class Vertex {
private Object num; //顶点的名称
public Link link; //链表,用来存放从该顶点出发的边的信息
public Vertex(Object num){
this.num=num;
link=new Link();
}
}
class Node {
private Object verNum; //顶点的名称
public Node next;
public Node(Object verNum){
this.verNum=verNum;
next=null;
}
public Object getVerNum() {
return verNum;
}
}
class Link {
Node current;
Node first;
public Link(){
current=null;
first=null;
}
//增加节点
public void add(Object num){
Node tempNode=new Node(num);
if(current==null){
current=tempNode;
first=tempNode;
}
else {
current.next=tempNode;
current=tempNode;
}
}
//遍历该链表 即遍历从某顶点出发的所有边
public void trackLink(int from){
Node cursor=first;
while(cursor!=null)
{
System.out.print(cursor.getVerNum()+" ");
cursor=cursor.next;
}
}
}
public class GraphReverse {
//图的顶点
Vertex[] vertexs;
//构建图,nums图中顶点的个数
public GraphReverse(int nums){
vertexs=new Vertex[nums+1];
for(int i=0;i<nums;i++) //顶点从0开始
vertexs[i]=new Vertex(i);
}
//增加边
public void addEdge(int from,int to){
vertexs[from].link.add(to);
}
//查找从某顶点出发的所有边
public void queryEdges(int VetexNum){
vertexs[VetexNum].link.trackLink(VetexNum);
}
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<Integer>();
list=Read("TXT/tinyDG.txt");
int n=list.get(0);
int o=list.get(1);
GraphReverse graph=new GraphReverse(n);
for(int j=2;j<=2*o;j=j+2){ //添加数组中顶点的关系到边
graph.addEdge(list.get(j), list.get(j+1));
}
/*for(int j=2;j<=2*o;j=j+2){ //构造反向图
graph.addEdge(list.get(j+1), list.get(j));
}*/
System.out.println("图的邻接表");
for(int i = 0;i < list.get(0);i++)
{
System.out.print(i+":");
graph.queryEdges(i);
System.out.print("\r\n");
}
}
public static ArrayList Read(String path){ //从文件中读取数据并存放到数组
ArrayList<Integer> list = new ArrayList<Integer>();
try{
BufferedReader reader = new BufferedReader(new FileReader(path));
String s;
String []str=null;
try{
while((s = reader.readLine()) != null){
str = (s.split(" "));
for(int i = 0;i < str.length;i++){
list.add(Integer.parseInt(str[i].trim()));
}
}
}catch (IOException e){
e.printStackTrace();
}
reader.close();
}catch (IOException e){
e.printStackTrace();
}
return list;
}
}
程序运行结果:
将100行的for循环注释,得到图的邻接表
将96行的for循环注释,去除100行的for循环注释,得到逆邻接表