栈的特点及优缺点
特点:先进后出,类似跌盘子,只能一个一个往上叠,取也只能一个接向下取;放到代码里,类似与函数调用,一层接一层
实现方式:
封装stack函数;数据存与数组中,实现push;pop;peek:返回栈顶元素;isEmpty;clear;size;
以下代码
function Stack() {
this.items = [];
this.length = 0
Stack.prototype.push = function (element) {
this.items.push(element)
this.length += 1
return this.items
}
Stack.prototype.pop = function () {
this.length -= 1
return this.items.pop()
}
Stack.prototype.peek = function () {
return this.items[this.length - 1]
}
Stack.prototype.isEmpty = function () {
return this.length === 0
}
Stack.prototype.clear = function () {
this.items = []
this.length = 0
}
Stack.prototype.size = function () {
return this.length
}
}
var stack = new Stack()
console.log(stack.push('a'))
console.log(stack.push('b'))
console.log(stack.push('c'))
console.log(stack.push('d'))
console.log(stack.push('e'))
console.log(stack.pop())
console.log(stack.peek())
console.log(stack.isEmpty())
console.log(stack.size())
console.log(stack.clear())