利用数组实现数据结构—栈

59 阅读1分钟

image.png

``

      function Stack() {
        this.items = []
        // push
        Stack.prototype.push = function (element) {
          this.items.push(element)
        }
        // pop
        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
        }
        // toString方法
        Stack.prototype.toString =function () {
          let resString = ''
          for(let i=0;i<this.items.length;i++) {
            resString += this.items[i]+''
          }
          return resString
        }
      }
      let s = new Stack()