JavaScript implements the detailed process of stack structure

JavaScript implements the detailed process of stack structure

1. Understanding the stack structure

We know that arrays are a common data structure, and data can be inserted and deleted at any position in the array. However, sometimes, in order to achieve certain functions, we must restrict this arbitrariness. Stacks and queues are relatively common restricted data structures. Let's take a look at the stack first.
A stack is a restricted linear table with a last-in-first-out ( LIFO ) order.

  • The restriction is that insertion and deletion operations are allowed at one end of the table. This end is called the top of the stack, and the other end is called the bottom of the stack.
  • LIFO (last in first out) means that the last element to enter is the first to be popped out of the stack space.
  • Inserting a new element into a stack is also called pushing, pushing or pushing. It is to put the new element on top of the top element of the stack, making it the new top element of the stack;
  • Deleting an element from a stack is also called making a stack or popping a stack. It is to delete the top element of the stack and make its adjacent element become the new top element of the stack.

Its structure diagram is as follows:

Similar to stack in life

For example: when we are typing code, if an error occurs and needs to be deleted, the first one typed in will be the last one to be deleted.

Next, let's implement the encapsulation of the stack structure together, and the method we will adopt is based on array.

2. Stack structure encapsulation

First, create a class encapsulating the stack structure as follows:

function Stack(){
            
        }

Add properties and methods inside it, and add the array to the class through the property methods. Then use the prototype method to add commonly used operations.

Common operations on stacks are:

  • push (element): Add a new element to the top of the stack.
  • pop() : Remove the top element of the stack
  • peek( ) : Returns the top element of the stack without modifying the stack.
  • isEmpty() : Determines whether the stack is empty. If there is no element in the stack, it returns true , otherwise it returns false
  • size() : Returns the number of elements in the stack
  • toString() : Returns the contents of the stack structure as characters

Next, we will implement them one by one:

 function Stack(){
     this.items = [];
     // Add a new element to the top of the stack. push()
     Stack.prototype.push = function(element){
        this.items.push(element);
     }
      // Remove the top element of the stack pop()
     Stack.prototype.pop = function(){
         return this.items.pop();
     }
     // Return the element at the top of the stack without making any modifications to the stack peek()
     Stack.prototype.peek = function(){
         return this.items[this.items.length-1];
     }
     // Determine whether the stack is empty isEmpty()
     Stack.prototype.isEmpty = function(){
         if (this.items.length == 0) {
             return true;
         }else {
             return false;
         }
     }
     // Return the number of elements in the stack size()
     Stack.prototype.size = function(){
         return this.items.length;
     }
     // Return the contents of the stack structure as characters toString()
     Stack.prototype.toString = function(){
         var str = '';
         for(var i =0;i<this.items.length;i++){
             str += this.items[i] + ' ';
         }
         return str;
     }
 }
       


Note: Why do we need to add it through the prototype here? This is because the methods added through this method are added to the class, and if they are added directly through this, they are added to the specific instance object, which will cause a waste of memory.

Finally, verify. The code is as follows:

var stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
console.log(stack);
console.log('The top element of the stack removed is: '+stack.pop());
console.log('The top element of the stack is: '+stack.peek());
console.log('Is the stack empty: '+stack.isEmpty());
console.log('The number of elements in the stack is: ' + stack.size());
console.log('The contents of the stack structure are:');
console.log(stack.toString());

The output is:

Build successful.
Let’s take a look at an example!

3. Convert decimal to binary

How to convert decimal to binary?

To convert decimal to binary, we can divide the decimal number by 2, push the remainder into the stack, until the result is 0, and finally pop the elements in the stack one by one to get the final result.

As shown in the following figure:

The specific code is:

 function Stack(){
     this.items = [];
     //Push into the stack Stack.prototype.push = function(element){
         this.items.push(element);
     }
     //Pop out Stack.prototype.pop = function(){
         return this.items.pop();
     }
     //Judge whether the stack is empty Stack.prototype.isEmpty = function(){
         if (this.items.length == 0) {
             return true;
         }else{
             return false;
         }
     }
 }
 function decToBin(decNumber){
      var stack = new Stack;
      while(decNumber>0){
          //Get the remainder and put it into the stack stack.push(decNumber%2);
          //Get the new divisor decNumber = Math.floor(decNumber/2);
      }
      //Get the top element of the stack var str = '';
      while(!stack.isEmpty()){
          str += stack.pop();
      }
      return str;
  }
 console.log('100 converted to binary is: '+decToBin(100));
 console.log('50 converted to binary is: '+decToBin(50));
 console.log('20 converted to binary is: '+decToBin(20));
 console.log('34 converted to binary is: '+decToBin(34));

The output is:

This is the end of this article about the detailed process of JavaScript implementing the stack structure. For more relevant JavaScript implementing the stack structure content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the process of implementing the stack structure in JavaScript
  • Detailed explanation of stack examples in JS algorithms and data structures
  • JS stack class implementation and usage examples
  • JavaScript data structure stack example usage

<<:  Some ways to solve the problem of Jenkins integrated docker plugin

>>:  Various methods to implement the prompt function of text box in html

Recommend

Complete steps of centos cloning linux virtual machine sharing

Preface When a Linux is fully set up, you can use...

mysql uses stored procedures to implement tree node acquisition method

As shown in the figure: Table Data For such a tre...

How to install mysql in docker

I recently deployed Django and didn't want to...

Solution to HTML2 canvas SVG not being recognized

There is a new feature that requires capturing a ...

Detailed Linux installation tutorial

(Win7 system) VMware virtual machine installation...

CSS and HTML and front-end technology layer diagram

Front-end technology layer (The picture is a bit e...

The most commonly used HTML escape sequence

In HTML, <, >, &, etc. have special mean...

Two usages of iFrame tags in HTML

I have been working on a project recently - Budou...

Life cycle and hook functions in Vue

Table of contents 1. What is the life cycle 2. Th...

JavaScript Basics Operators

Table of contents 1. Operators Summarize 1. Opera...

The difference between HTML name id and class_PowerNode Java Academy

name Specify a name for the tag. Format <input...

How to create a file system in a Linux partition or logical volume

Preface Learn to create a file system on your sys...

How to write high-quality JavaScript code

Table of contents 1. Easy to read code 1. Unified...

Analysis of Mysql transaction characteristics and level principles

1. What is a transaction? A database transaction ...