邻接表实现图,实际上是在一个数组里面存放链表,链表存放的是连接当前节点的其他节点。
package mygraph; import java.util.ArrayList;
import java.util.List; public class Table {
private List<List<Character>> list;
private List<Character> headNodes;
private int n;
private int nVerts;
//出始化链表
public Table() {
super();
this.list = new ArrayList<List<Character>>();
this.headNodes = new ArrayList<Character>();
list.add(new ArrayList<Character>());
list.add(new ArrayList<Character>());
list.add(new ArrayList<Character>());
list.add(new ArrayList<Character>());
}
//添加一个节点
public void addVertx(char x) {
headNodes.add(x);
}
//添加一条边
public void addEdge(int start, int end) {
list.get(start).add(headNodes.get(end));
list.get(end).add(headNodes.get(start));
} //打印节点
public void printVertice() {
for(List ls :list) {
for(Object i : ls) {
System.out.print(i + "\t");
}
System.out.println();
}
} }
测试程序:
public static void main(String[] args) {
Table t = new Table();
t.addVertx('a'); //
t.addVertx('b'); //
t.addVertx('c'); //
t.addVertx('d'); //
t.addEdge(0, 2);
t.addEdge(0, 1);
t.printVertice(); //0- b c //1- a //2- a
}
测试结果:
c b //a-c a-b
a //b-a
a //c-a