【数据结构】JavaScript Stack 实现

完整可运行代码

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

你可能感兴趣的:(javascript)