关于javascript:数据结构JavaScript-Stack-实现

34次阅读

共计 611 个字符,预计需要花费 2 分钟才能阅读完成。

残缺可运行代码

class Stack {constructor() {this.items = []
  }

  push(element) {this.items.push(element)
  }

  pop() {return this.items.pop()
  }

  peek() {return this.items[this.items.length-1]
  }

  isEmpty() {return this.items.length === 0}

  size() {return this.items.length}

  clear() {this.items = []
  }

  toString() {
    let resultString = ''
    for (const item of this.items) {resultString += item + ' '}
    return resultString
  }
}
// 
let stack = new Stack()
stack.push(1)
stack.push(2)
stack.push(3)
console.log(stack.items) //--> [1, 2, 3]

console.log(stack.pop()) //--> 3

console.log(stack.peek()) //--> 2

console.log(stack.isEmpty()) //--> false

console.log(stack.size()) //--> 2

console.log(stack.toString()); //--> 1 2

正文完
 0