/* 基于数组的栈 */
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
}
/* 清空栈元素 */
clear() {
this.items = []
}
/* 返回栈中元素的个数 */
size() {
return this.items.length
}
}
/* 基于JS对象的栈 */
class Stack {
constructor() {
this.count = 0
this.items = {}
}
/* 向栈添加元素 */
push(element) {
this.items[this.count] = element
this.count++
}
/* 从栈移除元素 */
pop() {
if (this.isEmpty()) {
return undefined
}
this.count--
const result = this.items[this.count]
delete this.items[this.count]
return result
}
/* 查看栈顶元素 */
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[this.count - 1]
}
/* 检查栈是否为空 */
isEmpty() {
return this.count === 0
}
/* 清空栈元素 */
clear() {
this.items = {}
this.count = 0
}
/* 返回栈中元素的个数 */
size() {
return this.count
}
}
Stack(栈)
最新推荐文章于 2024-09-02 17:34:07 发布