十字链表-js实现

/**
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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值