本篇文章给大家带来的内容是关于js实现链式栈的代码实例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
官方定义:链式栈是一种数据存储结构,可以通过单链表的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。
具体的实现
<!doctype html><html> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript"> function linkstack(){ this.length = 0; this.top = null;//栈顶指针 }; linkstack.prototype.node = function(el){ this.element = el; this.next = null; }; //压栈 linkstack.prototype.push = function(el){ var current, node = this.node, node = new node(el); if(!this.top){ this.top = node; this.length++; return true; }else{ current = this.top; node.next = current; this.top = node; this.length++; return true; } }; //退栈 linkstack.prototype.pop = function(){ var current = this.top; if(current){ this.top = current.next; current.next = null; this.length--; return current; }else{ throw "error null stack" } }; linkstack.prototype.tostring = function(){ var str = "", current = this.top; while(current){ str += current.element + " "; current = current.next; } return str; }; //清空栈 linkstack.prototype.clear = function(){ this.top = null; this.length = 0; return true; }; /***************测试代码******************/ function test(){ var linkstack = new linkstack(); //压栈 for(var i=1;i<21;i++){ linkstack.push(i); } console.log("压栈->" + linkstack.tostring()); //退栈 linkstack.pop(); linkstack.pop(); linkstack.pop(); console.log("退栈->" + linkstack.tostring()); //清空栈 linkstack.clear(); console.log("清空栈->" + linkstack.tostring()); } test(); </script> </head> <body> </body></html>
相关推荐:
js的代码如何进行压缩?js代码压缩的简单方法
nodejs中buffer是什么?nodejs中buffer类的用法
以上就是js实现链式栈的代码实例的详细内容。