JavaScript的数据结构-栈

67 阅读1分钟

前言

  栈是javascript中的一种重要的数据结构,他的特点是先进后出。对此,我封装了一系列的栈的API。对栈结构的一种总结。

        function Stack() {
            this.items = [];
            Stack.prototype.push = function (element) {
                this.items.push(element)
            }
            Stack.prototype.pop = function () {
                return this.items.pop();
            }
            Stack.prototype.peek = function () {
                return this.items[this.items.length - 1];
            }
            Stack.prototype.isEmpty = function () {
                return this.items.length === 0;
            }
            Stack.prototype.size = function () {
                return this.items.length;
            }
            Stack.prototype.toString = function () {
                let resultStr = '';
                for (let i = 0; i < this.items.length; i++) {
                    resultStr += this.items[i] + " ";
                }
                return resultStr;
            }
        }