js的链表

实验来源:https://blog.csdn.net/u010565037/article/details/65634325

一、html文件:Link.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="js/Link.js"></script>
    </head>
    <body>
        <h1>中华人民共和国</h1>
    </body>
</html>

二、js文件:Link.js

//建一个链表类
function Link(data,pre,next){
    this.data=data;
    this.preNode=pre;
    if(this.preNode){
        pre.nextNode=this;
    }
    this.nextNode=next;
}
//从第一个节点开始打印
Link.prototype.myPrint=function(){
    if(this.nextNode){
        console.log(this.data.name);
        return this.nextNode.myPrint();
    }else{
        return this.data.name;
    }
}
//增删改查
//从某一个节点的后面开始插入一个节点
Link.prototype.insertNode=function(node){
    //首先确定它是我的后面,我是它的前面。
    if(this.nextNode && this.nextNode.preNode){
        this.nextNode.preNode=node;
    }
    //站在node的角度,先把线牵起来再说!
    node.nextNode=this.nextNode;
    node.preNode=this;
    //最后才断开我与后一个节点的联系,这样,新节点就加入进来了。
    this.nextNode=node;
}
//删除某一个节点,点哪个删哪个
Link.prototype.removeNode=function(){
    this.nextNode.preNode=this.preNode;
    this.preNode.nextNode=this.nextNode;
}
//反序链表
Link.prototype.revertNode = function(){
     var tmp = null;//{nextNode: null, preNode: null};
     function revert(){
         if(!this.nextNode){
             this.preNode = null;
             this.nextNode = tmp;
             return this;
         }else{
             this.preNode = this.nextNode;
             this.nextNode = tmp;
             tmp = this;
             return revert.call(this.preNode);
         }
     }
     return revert.call(this);
}


var ln1=new Link({name:1},null,null);
var ln2=new Link({name:2},ln1,null);
var ln3=new Link({name:3},ln2,null);
var ln4=new Link({name:4},ln3,null);
var ln5=new Link({name:5},ln4,null);
var ln6=new Link({name:6},ln5,null);
var ln7=new Link({name:7},ln6,null);
var ln8=new Link({name:8},ln7,null);
//头节点
var lHead=ln1;
//建一个新节点
var yy=new Link({"name":100},null,null);
//在ln3节点的后面插入这个yy节点
ln3.insertNode(yy);
//删除ln7节点
ln7.removeNode();
//打印链表
console.log(lHead.myPrint());
//反序链表,它是一个新的链表,所以前面的var h= 不能少。
var h=lHead.revertNode();
console.log("反序打印");
console.log(h.myPrint());
 

猜你喜欢

转载自blog.csdn.net/jintingbo/article/details/82655308