//封装栈类
function Stack() {
this.items = []
//将元素压入栈中
Stack.prototype.push = function (element) {
return 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.length === 0
}
// 判断栈中的元素的个数
Stack.prototype.size = function () {
return this.items.length
}
// toString方法
Stack.prototype.toString = function () {
var resultstring = "";
for (var i = 0; i < this.items.length; i++) {
resultstring += this.items[i] + " "
}
return resultstring
}
}
var s = new Stack();
s.push(1);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.pop()
console.log(s);//1.3.4.5
console.log(s.peek());//5
console.log(s.isEmpty());//false
console.log(s.size());//4
console.log(s.toString());//1 3 4 5