The stack is a last-in-first-out data structure, but there is no such structure for our Javascript language, but we can implement it through the push and pop operations in the array
1. Implement the stack structure
const stack = []
stack.push(1)
stack.push (2)
const item1 = stack.pop()
const item2 = stack.pop()
2. Application scenarios
- Decimal to Binary
For converting from decimal to binary, we use the stack to push the number in by dividing the decimal number by 2 and take the remainder, and then use LIFO to pop out the stored number, which is the binary value.
- valid parentheses
According to the method of left bracket push and right bracket pop, the final array is empty to represent valid brackets
- function call stack
The last function called is executed first. The
JS parser uses the stack to control the calling sequence of the functions.const func1 = () => { func2() } const func2 = () => { func3() } const func3 = () => { } func1() // 先执行func1函数,再执行func2函数,再执行func3函数 //先执行完func3函数,再执行完func2函数,再执行完func3函数 // push func1 func2 func3 // pop func3 func2 func1
3. Practice
Implement a stack with ES6, class Stack
class Stack {
constructor() {
this.stack = []
this.top = 0
}
push(item) {
this.stack.push(item)
this.top ++
}
pop() {
this.top--;
return this.stack.pop()
}
peek() {
return this.stack[this.top - 1]
}
size() {
return this.top
}
clear() {
this.stack = []
}
}
Please use the stack data structure to convert the decimal number 100 to binary
function toTwo(num) {
var stack = []
while (num !== 0) {
stack.push(num % 2)
num = parseInt(num / 2)
}
return stack.reverse()
}
var res = toTwo(100).toString().replace(/,/g, "")