网上查了下,好像没找到比较满意的js栈实现,所以自己做了一个。
function stack() {
this.top = -1;
this.arr = new Array();
//避免为每个stack对象都创建函数
if(typeof stack._initialized == "undefined") {
stack.prototype.push = function (data) {
this.arr.push(data);
this.top++;
};
stack.prototype.pop = function () {
if(this.top < 0)
return false;
else{
res = this.arr[this.top];
this.arr.splice(this.top, 1);
this.top--;
return res;
}
};
stack.prototype.empty = function () {
if(this.top <= -1)
return true;
else
return false;
};
stack.prototype.clear = function () {
this.top = -1;
this.arr.splice(0,this.arr.length);
};
stack._initialized = true;
}
}