无向图的邻接表结构

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();   // 打印图
    }
}

猜你喜欢

转载自blog.csdn.net/Answer0902/article/details/82799417
今日推荐