數據結構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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM