Preliminary understanding of stack

Data structure: stack

  1. Is a lifO data structure
  2. JavaScript has no stack data structure
  3. But we can use Array to simulate the stack data structure

Diagram stack data structure

Examples of life see stack 😎

Let me give you an example. If your mom asked you to wash the dishes, you would have to do five dishes.

Is what meaning, you first wash the dishes must be under the minimum, then each other up, and finally finished washing the dishes must be placed on the top of the 😃 that when we need to use these plates, certainly also is each from the above, in turn, take a use take a use, isn’t it 😁 w but, if you tell me, You wash the dish is to follow place a minefield like, I still can say what, you can play bai 🤣

Stack data access

For the stack, it is similar to this brush plate put plate, each plate is actually equivalent to a data, the structure of these plates is the stack this data structure, of course, for the plate we have two basic operations to put and take, the same, for the stack, is nothing more than data access. How kind, see understand not 😁

In JavaScript to emulate stack data structure

We can debug with breakpoints to see changes in the data

const stack = [];
stack.push(1);
stack.push(2);
const item1 = stack.pop();
const item2 = stack.pop();
Copy the code

LeetCode: 20. Valid parentheses

var isValid = function(s) { if(s.length%2 === 1) return false const stack = []; for(let i = 0; i < s.length; i ++){ const c = s[i]; if(c==='(' || c === '{' || c === '['){ stack.push(c) } else { //) } const t = stack[stack.length - 1];  // console.log(stack.length) // console.log(t) console.log(c) if( (t === '(' && c === ')') || (t === '{' && c === '}') || (t === '[' && c === ']') ){ stack.pop() } else { return false; } } } return stack.length === 0; };  console.log(isValid("[")) console.log(isValid("({[]})")) console.log(isValid("[]{}()"))Copy the code

Let’s take a look at the schematic of the queue:

Here in the team, out of the team, team tail and team head should be good to understand ah, looking at the figure at a glance ah, this is the queue, so a look, is not the feeling queue or simple ah, in fact about the concept of the queue, really not what difficult 😀

Life case

Queuing for tickets at the station

Whoever got the tickets first came outDo you have a general understanding of it now?