Home >Web Front-end >JS Tutorial >Code example of js implementing chain stack
This article brings you code examples about JS implementation of chain stack. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Official definition: The chain stack is a data storage structure that can be implemented through a single linked list. The advantage of using the chain stack is that it can overcome the low space utilization of the sequential stack implemented with an array. feature, but additional pointer space needs to be allocated for each stack element to store the pointer field.
# specific implementation
<!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>
Related recommendation:
js code How to compress the code? A simple method to compress js code
What is buffer in Nodejs? Usage of buffer class in Nodejs
The above is the detailed content of Code example of js implementing chain stack. For more information, please follow other related articles on the PHP Chinese website!