/**
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();
十字链表-js实现
最新推荐文章于 2021-07-04 21:55:13 发布