search
HomeWeb Front-endJS TutorialHow to implement a stack in JavaScript

How to implement a stack in JavaScript

Jul 11, 2018 pm 04:54 PM
javascriptfront endData Structures and Algorithms

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

How to implement a stack in JavaScript

  • #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:

How to implement a stack in JavaScript

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中文网!

相关推荐:

如何利用js fetch实现ping效果

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.