时间:2021-07-01 10:21:17 帮助过:2人阅读
官方定义:链式栈是一种数据存储结构,可以通过单链表的方式来实现,使用链式栈的优点在于它能够克服用数组实现的顺序栈空间利用率不高的特点,但是需要为每个栈元素分配额外的指针空间用来存放指针域。
具体的实现
<!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实现链式栈的代码实例的详细内容,更多请关注Gxl网其它相关文章!