标签:
我们通常会在c++这类语言中学习到链表的概念,我打算用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 }
为了便于观察结果,我们再写一个打印链表的函数,挂在原型上:
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
大功告成!
标签:
原文地址:http://www.cnblogs.com/webARM/p/5425190.html