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
  }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容