// 基于数组实现栈结构
function Stack() {
this.items = []
// 类的方法挂载到prototype可以实现共享,可以节省内存
// 压栈
Stack.prototype.push = function(element) {
this.items.push(element)
}
// 弹栈并返回
Stack.prototype.pop = function() {
return this.items.pop()
}
// 查看栈顶元素
Stack.prototype.peek = function() {
return this.items[this.items.length-1]
}
// 判断是否为空
Stack.prototype.isEmpty = function() {
return this.items === 0
}
// 获取栈元素个数
Stack.prototype.size = function() {
return this.items.length
}
// toString方法
Stack.prototype.toString = function() {
return this.items.join(' ')
}
}
let s = new Stack()
s.push(1)
s.push(3)
s.push(8)
s.push(7)
s.push(9)
s.push(10)
console.log(s.toString());
console.log(s.peek());
console.log(s.pop());
console.log(s.toString());
javascript栈实现
最新推荐文章于 2024-01-31 11:40:51 发布