开发者社区 问答 正文

用JavaScript实现一个栈结构?

展开
收起
前端问答 2020-01-02 12:20:45 4817 分享 版权
1 条回答
写回答
取消 提交回答
  • 前端问答小助手

    每种数据结构都可以用很多种方式来实现,其实可以把栈看成是数组的一个子集,所以这里使用数组来实现

    class Stack {
      constructor() {
        this.stack = []
      }
      push(item) {
        this.stack.push(item)
      }
      pop() {
        this.stack.pop()
      }
      peek() {
        return this.stack[this.getCount() - 1]
      }
      getCount() {
        return this.stack.length
      }
      isEmpty() {
        return this.getCount() === 0
      }
    }
    
    2020-01-02 12:21:18
    赞同 1 展开评论