js 用数组实现栈结构

96 阅读1分钟
    // 实现栈结构的基本功能
    function Stack() {
        this.items = [];
        // 1. push(element) 入栈操作
        Stack.prototype.push = function (element) {
            this.items.push(element);
        }
        // 2. pop() 出栈操作
        Stack.prototype.pop = function () {
            return this.items.pop();
        }
        // 3. size() 返回栈数量
        Stack.prototype.size = function () {
            return this.items.length;
        }
        // 4. isEmpty() 是否为空栈
        Stack.prototype.isEmpty = function () {
            return this.items.length === 0;
        }
        // 5. peek()  查看栈顶元素
        Stack.prototype.peek = function () {
            return this.items[this.items.length-1];
        }
        // 6. toString() 方法
        Stack.prototype.toString = function () {
            let result = ''
            for (let i = 0; i < this.items.length; i++){
                let sign = this.items.length-1 === i ? '':','
                result += this.items[i] + sign;
            }
            return result;
        }

    }

    let stack = new Stack();