無向圖的鄰接表結構
阿新 • • 發佈:2018-12-11
public class LinkUDG { private class Enode{//邊表 int pos;//儲存某頂點的鄰接點在頂點表中的下標 Enode nextNode;//指向下一個節點 } private class Vnode{//頂點表 String data;//頂點的資料 Enode firstNode;//指向此頂點的第一個臨界點 } private Vnode[] top;//頂點陣列 public LinkUDG(String[] vexs,String[][] edges){ int vlen=vexs.length; int elen=edges.length; //初始化頂點 top=new Vnode[vlen]; for(int i=0;i<vlen;i++){ top[i]=new Vnode(); top[i].data=vexs[i]; top[i].firstNode=null; } //初始化邊 for(int i=0;i<elen;i++){ int p1=getPos(edges[i][0]); int p2=getPos(edges[i][1]); Enode eNode=new Enode(); eNode.pos=p2; if(top[p1].firstNode==null){ top[p1].firstNode=eNode; }else{ addTail(top[p1].firstNode, eNode); } Enode eNode1=new Enode(); eNode1.pos=p1; if(top[p2].firstNode==null){ top[p2].firstNode=eNode1; }else{ addTail(top[p2].firstNode, eNode1); } } } private void addTail(Enode list,Enode node){ Enode temp=list; while(list.nextNode!=null){ list=list.nextNode; } temp.nextNode=node; } private int getPos(String ch){//得到邊頂點的位置 for(int i=0;i<top.length;i++){ if(top[i].data.equals(ch)){ return i; } }return -1; } public void print() { System.out.printf("List Graph:\n"); for(int i=0;i<top.length;i++){ System.out.printf("%d(%s): ",i,top[i].data); Enode enode=top[i].firstNode; while(enode!=null){ System.out.printf("%d(%s) ", enode.pos, top[enode.pos].data); enode = enode.nextNode; } System.out.println(); } } public static void main(String[] args) { String[] vexs = {"V0", "V1", "V2", "V3"}; String[][] edges = new String[][]{//無向圖,全部表示節點之間的關係即可 {"V0", "V1"}, {"V0", "V2"}, {"V0", "V3"}, {"V1", "V2"}, {"V3", "V2"} }; // 自定義"圖"(輸入矩陣佇列) //pG = new ListUDG(); // 採用已有的"圖" LinkUDG pG = new LinkUDG(vexs, edges); pG.print(); // 列印圖 } }