JavaScript 数据结构——栈

概念

栈是一种线性结构,最大的特点就是先进后出,后进先出

入栈push()

出栈pop()

实现

JavaScript中可以用数组表示栈:

class Stack {
    
    
    constructor() {
    
    
        this.stack = [];
    }
    push(item) {
    
    
        // 入栈
        this.stack.push(item)
    }
    pop() {
    
    
        // 出栈
        this.stack.pop()
    }
    getCount() {
    
    
        // 获取栈大小
        return this.stack.length
    }
    peek() {
    
    
        // 获取栈顶元素
        return this.stack[this.getCount() - 1]
    }
    isEmpty() {
    
    
        // 判断是否为空栈
        return this.stack.length === 0
    }
}

猜你喜欢

转载自blog.csdn.net/Jack_lzx/article/details/114760521