實現簡單,不多解釋了,使用數組來保存數據
function Stack () {
var items = [];
//入棧
this.push = function (item) {
items.push(item);
}
// 出棧
this.pop = function () {
return items.pop();
}
// 返回棧頂的元素
this.peek = function () {
return items[items.length - 1];
}
// 判斷棧是否爲空
this.isEmpty = function () {
return items.length == 0
}
// 清棧
this.clear = function () {
items = [];
}
// 棧的大小
this.size = function () {
return items.length
}
// 打印棧的內容
this.print = function () {
console.log(items);
}
}