JavaScript不用数组实现栈的方式

class Stack {
  constructor() {
    this.item={}
    this.count=0
  }
  //栈顶添加
  push(item){
    this.item[this.count]=item
    this.count++
  }
  //删除
  pop(){
    if(this.isEmpty()){
      return undefined
    }
    this.count--
    const result = this.item[this.count]
    delete this.item[this.count]
    return result
  }
  //查看栈顶元素
  peek() {
    if(this.isEmpty()){
      return undefined
    }
    return this.item[this.count]
  }
  //清空栈
  clear() {
    this.item = {}
    this.count=0
  }
  //栈是否为空
  isEmpty() {
    return this.count===0
  }
  //查看栈长度
  size(){
    return this.count
  }
  //创建toString方法
  toString() {
    if (this.isEmpty()) {
      return ``
    }
    let str = `${this.item[0]}`
    for (let i =1;i < this.count; i++){
      str+=`,${this.item[i]}`
    }
    return str
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容