十字链表-js实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhoujiaping123/article/details/81008440
/**
https://blog.csdn.net/dongyanxia1000/article/details/53584496
*/
function newAcrosslinker(){
    let vs = [];//顶点数组
    let al = {//十字链表
        vs:vs,
        /**设置顶点个数*/
        setVertexNum(vn){
            for(let i=0;i<vn;i++){
                vs.push({
                    firstin:null,
                    firstout:null
                });
            }
        },
        /**添加一条边*/
        addEdge(i,j,w){
            let node = {i,j,w};
            //设置出度
            if(!vs[i].firstout){
                vs[i].firstout = node;
            }else{
                let nextout = vs[i].firstout;
                while(nextout.nextout){
                    nextout = nextout.nextout;
                }
                nextout.nextout = node;
            }
            //设置入度
            if(!vs[j].firstin){
                vs[j].firstin = node;
            }else{
                let nextin = vs[j].firstin;
                while(nextin.nextin){
                    nextin = nextin.nextin;
                }
                nextin.nextin = node;
            }
        },
        /**获取顶点j的入度数组*/
        getIns(j){
            let ins = [];
            let nextin = this.vs[j].firstin;
            while(nextin){
                ins.push(nextin);
                nextin = nextin.nextin;
            }
            return ins;
        },
        /**获取顶点i的出度数组*/
        getOuts(i){
            let outs = [];
            let nextout = this.vs[i].firstout;
            while(nextout){
                outs.push(nextout);
                nextout = nextout.nextout;
            }
            return outs;
        }
    };
    return al;
}
function test(){
    let al = newAcrosslinker();
    al.setVertexNum(4);
    al.addEdge(1,2,4);
    al.addEdge(2,0,5);
    al.addEdge(2,1,6);
    al.addEdge(0,3,2);
    al.addEdge(1,0,3);

    console.info(JSON.stringify(al.vs,null,2));
    al.vs.forEach((v,i)=>{
        console.info(`ins for ${i}:`);
        console.info(al.getIns(i).map(node=>node.i));
    });
    al.vs.forEach((v,i)=>{
        console.info(`outs for ${i}:`);
        console.info(al.getOuts(i).map(node=>node.j));
    });

    /*
    for(let i=0;i<al.vs.length;i++){
        let ins = [];
        let nextin = al.vs[i].firstin;
        while(nextin){
            ins.push(nextin.i);
            nextin = nextin.nextin;
        }
        console.info(`ins for ${i}:`);
        console.info(ins);

    }*/
}
test();

猜你喜欢

转载自blog.csdn.net/zhoujiaping123/article/details/81008440