1. 程式人生 > >js的連結串列

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());