js 實現鏈表


我們通常會在c++這類語言中學習到鏈表的概念,但是在js中由於我們可以動態的擴充數組,加之有豐富的原生api。我們通常並不需要實現鏈表結構。由於突發奇想,我打算用js實現一下:

首先我們要創建鏈表:

1 //創建鏈表
2 function CreateLinkNode(data, pre, next){
3     this.data = data;
4     this.preNode = pre;
5     if(this.preNode){
6         pre.nextNode = this;
7     }
8     this.nextNode = next;
9 }

鏈表最基本的要包括數據部分(data)、指向前一個的指針(preNode)、指向后一個的指針(nextNode)。

 

為了便於觀察結果,我們再寫一個打印鏈表的函數,掛在原型上:

1 //從模一個節點開始打印鏈表
2 CreateLinkNode.prototype.print = function(){
3     
4     if(this.nextNode){
5         return this.data.name + this.nextNode.print();
6     }else{
7         return this.data.name;
8     }
9 }

打印的函數由某一個節點調用,遞歸調用,拼裝從此之后的所有節點的數據部分。

 

增刪改查都要有吧:

 1 //從某一個節點的后面開始插入一個節點
 2 CreateLinkNode.prototype.insertNode = function(node){
 3     if(this.nextNode && this.nextNode.preNode){
 4         this.nextNode.preNode = node;
 5     }
 6     
 7     node.nextNode = this.nextNode;
 8 
 9     node.preNode = this;
10     this.nextNode = node;
11 }
12 
13 //刪除某一個節點
14 CreateLinkNode.prototype.removeNode = function(){
15     this.nextNode.preNode = this.preNode;
16     this.preNode.nextNode = this.nextNode;
17 }

插入節點: 在當前的節點后面插入一個節點對象。注意一下,如果當前節點是尾節點時的單獨處理。

刪除節點: 把當前節點刪除,並鏈接后面的節點。

 

還要有最不能少的反序:

 1 //反序鏈表
 2 CreateLinkNode.prototype.revertNode = function(){
 3     var tmp = null;//{nextNode: null, preNode: null};
 4     function revert(){
 5         if(!this.nextNode){
 6             this.preNode = null;
 7             this.nextNode = tmp;
 8             return this;
 9         }else{
10             this.preNode = this.nextNode;
11             this.nextNode = tmp;
12             tmp = this;
13             return revert.call(this.preNode);
14         }
15     }
16 
17     return revert.call(this);
18 
19 }

保證鏈表基本機構不變,並要返回新的頭節點(原來的尾節點)。和對尾節點的單獨處理。

 

我們來測試一下(好激動)

 1 //  start
 2 var ln1 = new CreateLinkNode({"name": "1"}, null, null);
 3 var ln2 = new CreateLinkNode({"name": "2"}, ln1, null);
 4 var ln3 = new CreateLinkNode({"name": "3"}, ln2, null);
 5 var ln4 = new CreateLinkNode({"name": "4"}, ln3, null);
 6 var ln5 = new CreateLinkNode({"name": "5"}, null, null);
 7 var lHead = ln1;
 8 ln4.insertNode(ln5);
 9 
10 console.log(lHead.print());//12345
11 
15 ln3.removeNode();
16 console.log(lHead.print());// 1245
17 ln2.insertNode(ln3);
18 console.log(lHead.print());// 12345
19 lHead = lHead.revertNode();
20 console.log(lHead.print());// 54321

大功告成!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM