Javascript 基于数组的方式实现栈及其一系列相关的操作
代码实现:
//封装栈类
function Stack() {
this.items = []
//栈的相关操作
//1、将元素压入栈
Stack.prototype.push = function (element) {
this.items.push(element)
}
//2、将元素出栈
Stack.prototype.pop = function () {
return this.items.pop()
}
//3、查看栈顶元素
Stack.prototype.peek = function () {
return this.items[this.items.length - 1]
}
//4、判断栈是否为空
Stack.prototype.isEmpty = function () {
return this.items.length === 0
}
//5、回去栈中元素的个数
Stack.prototype.size = function () {
return this.items.length
}
//6、将栈中元素以字符串的方式返回
Stack.prototype.toString = function () {
let resultString = ''
for (let i = 0 ; i < this.items.length ; i++) {
resultString += this.items[i] + ' '
}
return resultString
}
}
const s = new Stack()
s.push(12)
s.push(56)
s.push(100)
s.push(89)
s.push(789)
let a = s.pop()
console.log(a)
console.log(s.items)
console.log(s.peek())
console.log(s.size())
console.log(s.isEmpty())
console.log(s.toString())
结果如下:
789
[ 12, 56, 100, 89 ]
89
4
false
12 56 100 89