完整可运行代码
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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。