栈
栈是一种操作受限的线性结构,遵循后进先出的原则。
基本的操作包括入栈,出栈等。
js实现
使用构造函数
function Stack() {
let items = []
this.pop = function () {
return items.pop()
}
this.push = function (element) {
items.push(element)
}
this.size = function () {
return items.length
}
// 清除栈
this.clear = function () {
items = []
}
this.isEmpty = function () {
return items.length == 0
}
// 获取栈顶的元素
this.peek = function () {
return items[items.length - 1]
}
this.print = function () {
console.log(items.toString())
}
}
使用构造函数初始化栈,内部用数组保存栈的数据,实现了入栈,出栈,获取栈顶元素,清空栈等操作。
es6Stack类
class Stack{
constructor(){
this.items = []
}
pop = function () {
return this.items.pop()
}
push = function (element) {
this.items.push(element)
}
size = function () {
returnthis. items.length
}
// 清除栈
clear = function () {
this.items = []
}
isEmpty = function () {
return this.items.length == 0
}
// 获取栈顶的元素
peek = function () {
return this.items[this.items.length - 1]
}
print = function () {
console.log(this.items.toString())
}
}
使用es6的类实现栈,和构造函数差别不大。