鄰接表實現圖,其實是在一個數組裏面存放鏈表,鏈表存放的是鏈接當前節點的其餘節點。java
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'); //0 t.addVertx('b'); //1 t.addVertx('c'); //2 t.addVertx('d'); //3 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