How to implement a stack in JavaScript
This article mainly introduces how to use JavaScript to implement a stack, which has certain reference value. Now I share it with you. Friends in need can refer to it
What is a stack
#The stack is an ordered collection that follows the last-in-first-out (LIFO) principle.
Newly added or to be deleted elements are stored at the end of the stack, which is called the top of the stack, and the other end is called the bottom of the stack.
In the stack, new elements are close to the top of the stack, and old elements are close to the bottom of the stack
Real-life examples
You can also find many examples of stacks in life. For example, among the plates stacked in the kitchen, the ones stacked on top are always used first; when the content of the input box is deleted, the last input is always deleted first; the bullets in the magazine are fired first as they are loaded later. ....
Manually implement a stack
First, create a class to represent the stack
function Stack () { }
We need to choose a data structure to save the elements in the stack, you can Select the array
function Stack(){ var items = []; //用来保存栈里的元素 }
Next, add some methods to the stack
push(element(s)); //添加新元素到栈顶 pop(); //移除栈顶的元素,同时返回被移除的元素 peek(); //返回栈顶的元素,不对栈做任何修改 isEmpty(); //如果栈里没有任何元素就返回true,否则false clear(); //移除栈里的所有元素 size(); //返回栈里的元素个数,类似于数组的length属性
The first method we need to implement ispush
. Used to add new elements to the stack, one thing is very important: this method only adds to the top of the stack, which is the end of the stack. Therefore, you can write like this:
this.push = function (element) { items.push(element); }
Using the push method of the array, you can add new elements to the end of the top of the stack.
Next, implement the pop
method to remove elements from the stack. The stack follows the LIFO (last in, first out) principle. What is removed is the last element added. Therefore, you can use the pop method of the array.
this.pop = function () { return items.pop(); }
In this way, this stack naturally follows the LIFO principle
Now, let’s add additional auxiliary methods to this stack.
If you want to know what the last element added to the stack is, you can use the peek
method. This method will return the element on the top of the stack
this.peek = function () { return items[items.length-1]; }
Because the class uses an array to save the elements, so here to access the last element of the array use length-1
Next The method to be implemented is isEmpty
. If the stack is empty, it returns true, otherwise it returns false:
this.isEmpty = function () { return items.length == 0; }
Using the isEmpty method, you can simply determine whether the stack is empty.
Similar to the length property of the array, we can also implement the length of the stack.
this.size = function () { return items.length; }
Because the stack uses an array internally to store elements, the length of the array is the length of the stack.
Implement the clear
method. The clear method is used to clear all elements in the stack. The simplest implementation method is:
this.clear = function () { items = []; }
In fact, it is also possible to call the pop method multiple times, but it is not as simple and fast as this method.
Finally, in order to check the contents of the stack, you need to implement an auxiliary method: print
. It will output all the elements in the stack to the console:
this.print = function () { console.log(items.toString()); }
At this point, we have completely created a stack!
The complete code of the stack
function Stack(){ var items = []; //用来保存栈里的元素 this.push = function (element) { items.push(element); } this.pop = function () { return items.pop(); } this.peek = function () { return items[items.length-1]; } this.isEmpty = function () { return items.length == 0; } this.size = function () { return items.length; } this.clear = function () { items = []; } this.print = function () { console.log(items.toString()); } }
Using the Stack class
The stack has been created, let’s test it
First, initialize the Stack class. Then, verify whether the stack is empty
var stack = new Stack(); console.log(stack.isEmpty()); //控制台输出true
Next, add an element to the stack:
stack.push(5); stack.push(8);
If you call the peek method, it will obviously output 8, because it is on the top of the stack Element:
console.log(stack.peek()); //控制台输出8
Add another element:
stack.push(11); console.log(stack.size()); //控制台输出3
We added another 11 to the stack. If the size method is called, the output is 3 because there are three elements on the stack (5, 8, and 11). If you call the isEmpty method at this time, you will see false output (because the stack is not empty at this time). Finally, add another element to it:
stack.push(15);
Then, call the pop method twice to remove two elements from the stack:
stack.pop(); stack.pop(); console.log(stack.size()); //控制台输出2 stack.print(); //控制台输出[5,8]
At this point, the functional test of the entire stack is completed.
Use the stack to solve the problem
Use the stack to complete the hexadecimal conversion.
In real life, we mainly use decimal system, but in computing science, binary system is very important, because all contents in the computer are represented by binary numbers 0 and 1. Computer classes in universities will first teach base conversion. Take binary as an example:
function pideBy2 (decNumber) { var remStack = new Stack(), rem, binaryString = ''; while (decNumber>0) { //{1} rem = Math.floor(decNumber % 2); //{2} remStack.push(rem); //{3} decNumber = Math.floor(decNumber / 2); //{4} } while (!remStack.isEmpty()) { //{5} binaryString += remStack.pop().toString(); } return binaryString; }
In this code, when the result meets the condition of being divisible by 2, (line {1}), we will get the current result and The remainder of 2 is placed on the stack (lines {2}, {3}). Then let the result be evenly divided by 2 (line {4})
Note: JavaScript has a numeric type, but it does not distinguish between integers and floating point numbers. Therefore, use the Math.floor function to make the division operation return only the integer part.
Finally, use the pop method to remove all elements from the stack, and concatenate the popped elements into strings (line {5}).
Test it:
console.log(pideBy2(520)); //输出1000001000 console.log(pideBy2(10)); //输出1010 console.log(pideBy2(1000)); //输出1111101000
Next, you can easily modify the above algorithm so that it can convert decimal to any base. In addition to converting decimal numbers and divisibility by 2 into binary numbers, you can also pass in other arbitrary bases as parameters, just like the following algorithm:
function baseConverter (decNumber, base) { var remStack = new Stack(), rem, baseString = ''; digits = '0123456789ABCDEF'; //{6} while (decNumber>0) { rem = Math.floor(decNumber % base); remStack.push(rem); //{3} decNumber = Math.floor(decNumber / base); } while (!remStack.isEmpty()) { baseString += digits[remStack.pop()]; //{7} } return baseString; }
在将十进制转成二进制时,余数是0或1;在将十进制转成八进制时,余数时0-8之间的数;但是将十进制转成十六进制时,余数时0-9之间的数字加上A、B、C、D、E、F(对应10、11、12、13、14和15)。因此,需要对栈中的数字做个转化才可以(行{6}、{7})。
来测试一下输出结果:
console.log(baseConverter(1231,2)); //输出10011001111 console.log(baseConverter(1231,8)); //输出2317 console.log(baseConverter(1231,16)); //输出4CF
显然是正确的。
小结
我们用js代码自己实现了栈。并且通过进制转换的例子来实际应用了它。栈的应用实例还有很多,比如平衡圆括号和汉诺塔。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of How to implement a stack in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

In Java, performance optimization can be achieved through the following steps: analyze data to understand its characteristics; select algorithms suitable for specific tasks; use optimization techniques to improve data structure performance; understand optimization methods with the help of practical cases (such as using binary search trees to optimize searches) ; Conduct benchmarking and analysis to quantify improvements; Avoid over-optimization to maintain code simplicity.

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn
