栈
function Stack() {
var items = []
// push: 添加一个或是几个新元素到栈顶
this.push = function(element) {
items.push(element)
}
// pop: 移除栈顶的元素,同时返回被移除的元素
this.pop = function(element) {
return item.pop()
}
// peek: 返回栈顶的元素,但并不对栈顶的元素做出任何的修改
this.peek = function() {
return items[items.length - 1]
}
// isEmpty: 检查栈内是否有元素
this.isEmpty = function() {
retrun items.length === 0
}
// clear: 清除栈内的元素
this.clear= function() {
items = []
}
// size: 返回栈内的元素个数
this.size = function() {
retrun items.length
}
// print: 打印栈内的元素
this.print = function () {
console.log(items.toString())
}
}
队列
function Queue() {
var items = []
// enqueue: 向队列尾部添加一个或多个元素
this.enqueue = function(element) {
items.push(element)
}
// dequeue: 移除队列的第一个元素,并返回被移除的元素
this.dequeue = function() {
return items.shift()
}
// front: 返回队列的第一个元素--最先被添加的也是最先被移除的元素。队列不做任何变动
this.front = function() {
return items[0]
}
// isEmpty: 检查队列内是否有元素
this.isEmpty = function() {
return items.length === 0
}
// size: 返回队列的长度
this.size = function() {
return items.length
}
// print: 打印队列的元素
this.print = function() {
console.log(items.toString()
}
}