[resolve data structure] what is stack? Handwriting implements a stack structure

Hello, I'm Xiaocheng, a sophomore front-end enthusiast This article will explain stack in data structure Thank you very much for reading. You are welcome to correct the wrong places May you be loyal to yourself and love life

Content first

  • What is a stack?
  • What are the methods of stack structure
  • Implement a stack
  • LeetCode actual combat

Broken thoughts

This article will summarize the first data structure learned: stack. Stack is also widely used in the front end, such as function call stack, hexadecimal conversion and valid parentheses Let's have a look

1, What is stack structure?

Stack is a special linear list, which can be implemented by array or linked list. It is usually implemented by array, but it is very different from array. For arrays, we can take an element out of the array at will, or insert an element at any position in the array. However, for the stack structure, there are certain restrictions relative to the array, which only allows fetching and inserting operations at the top of the stack Therefore, the stack has the characteristics of first in and last out

As shown in the figure, a stack structure can be vividly described

This is like a bucket in life. You can only put things in from the mouth and take things out from the top of the bucket

There are many examples in life, such as the badminton bucket. We can only take the top badminton and put it on the top every time

Therefore, a stack can be divided into top and bottom

The stack top can be understood as the bucket mouth

The bottom of the stack can be the bottom of the bucket

In JS, the familiar execution context is also maintained using the stack structure. At the bottom of the stack is the global scope (GO). The execution context of the current execution code is added to the stack in turn, and the element at the top of the stack is always the executing context object.

2, What are the methods of stack structure?

Like the general data structure, it has the methods of insertion and extraction. We call them: in stack and out stack In order to enrich the methods in the stack, we need to implement more. For example, judge whether the top of the stack is empty, return the number of elements in the stack, empty the stack, and return the top of the stack elements

method

meaning

push()

Add a new element to the top of the stack

pop()

Remove the top element of the stack and return the removed element

peek()

Returns the top element of the stack without changing the stack

isEmpty()

Determine whether the stack is empty

clear()

Remove all elements from the stack

size()

Returns the number of elements in the stack

Next, we will implement them one by one

👇 👇 👇

3, Handwriting implements a stack structure

Here, I use array to realize the data structure of stack, because JS array encapsulates a large number of native API s, which can easily realize our functions

1. Create a Stack class

First, we create a class class and use the stackData array to store our data

class Stack {
  constructor() {
    this.stackData = [];
  }
}

2. Implement the push method

To realize the method of stacking, here is the advantage of using array According to the rules of the stack, we can only add elements at the top of the stack, that is, insert them at the last bit of the array, corresponding to the push method of the array Therefore, the stack method that implements the stack structure is to call the push method of the array

push(element) {
    this.stackData.push(element)
}

3. Implement pop method

To realize the method of out of the stack, according to the principle of last in first out, that is, taking out the top element of the stack is equivalent to taking out the last bit of the array Therefore, we can use the pop method of array to implement it

pop method: deletes the last bit of the array and returns the deleted value

pop() {
    this.stackData.pop()
}

A simple stack structure has been basically implemented. Let's try to operate it

First, we need an object example of new, and then call the following methods appropriately to demonstrate it

const stack = new Stack()
stack.push(9)
stack.push(4)
stack.pop()
stack.push(6)

Moving picture effect

You can see that elements are added at the end of the array every time. pop is also the element at the end of the array

4. Implement peek method

peek is to view the element at the top of the stack, that is, the last element of the array. At the same time, this operation will not change the stack. Oh ~ just view

The implementation method is also very simple. We just need to return the last bit of the array

peek() {
    return this.stackData[this.stackData.length - 1]
}

Using peek method

const stack = new Stack()
stack.push(9)
stack.peek() // 9

5. Implementation method

size method: returns the number of elements in the stack, that is, the length of the array

size() {
    return this.stackData.length
}

Call the size method

const stack = new Stack()
stack.push(9)
stack.push(4)
stack.size() // 2

6. Implement isEmpty method

isEmpty method: check whether there is a value in the current stack. If it is empty, return true

Let's just judge the length directly

isEmpty() {
    return !this.stackData.length
}

Using isEmpty method

const stack = new Stack()
stack.push(9) 
stack.isEmpty()  // false is not empty

7. Implement the clear method

Clear method: clear the stack, that is, reset the stack

clear() {
    this.stackData = []
}

8. Complete stack structure

class Stack {
    constructor() {
        this.stackData = []
    }
    // Push 
    push(element) {
        this.stackData.push(element)
    }
    // Out of stack
    pop() {
        this.stackData.pop()
    }
    // Get stack top
    peek() {
        return this.stackData[this.stackData.length - 1]
    }
    // Check whether it is empty
    isEmpty() {
        return !this.stackData.length
    }
    // Empty stack
    clear() {
        this.stackData = []
    }
    // Returns the number of elements
    size() {
        return this.stackData.length
    }
}

4, LeetCode actual combat

20. Valid brackets

Given a string s that only includes' (',') ',' {','} ',' [','] ', judge whether the string is valid. Valid strings must meet the following requirements: the left parenthesis must be closed with the same type of right parenthesis. The left parentheses must be closed in the correct order.

This is a very classic problem. We can use the last in first out feature of the stack to solve the problem, because we need to match the left and right parentheses

  • When we encounter an open parenthesis, we put it on the stack
  • When encountering the right bracket, we need to judge whether the current stack top matches this bracket
  • If it matches, it indicates that it meets the requirements and continues to traverse. If it does not match, it directly returns false
  • There is also a special case, when the length of the input string s is an odd number, it is impossible to meet the meaning of the question

So we can write code

var isValid = function (s) {
    // Create a new stack
    const stack = [];
    // Scan the string, enter the stack when encountering the left bracket, and exit the stack when encountering the right bracket that matches the type of the bracket at the top of the stack. If the type does not match, it is directly false
    for (let i = 0; i < s.length; i++) {
        // If it is an odd number, false will pop up directly
        if (s.length % 2 === 1) {
            return false
        }
        const c = s[i];
        // Left parenthesis push encountered
        if (c === '(' || c === '{' || c === '[') {
            stack.push(c)
        } else {
            const t = stack[stack.length - 1]
            if (
                (t === '(' && c === ')')||
                (t === '[' && c === ']')||
                (t === '{' && c === '}')
            ) {
                stack.pop()
            } else {
                return false
            }

        };
    }
    return stack.length === 0
}

summary

  1. An array is used to encapsulate a stack structure
  2. Understand the basic method of stack structure
  3. Have a better understanding of data structure

That's the end of this article. I'm sure you can learn a lot from it.

Posted on Fri, 12 Nov 2021 13:55:24 -0500 by stfuji