您的位置:首页 > 理论基础 > 数据结构算法

js数据结构——栈

2017-01-22 00:00 78 查看
摘要: js数据结构——栈

function Stack(){
var items = [];
//动态原型模式
if(typeof this.pop != "function"){
//入栈
Stack.prototype.push = function(element){
items.push(element);
}
//出栈
Stack.prototype.pop = function(){
return items.pop();
}
//返回栈顶的元素
Stack.prototype.peek = function(){
return items[items.length-1];
}
//判断是否栈空
Stack.prototype.isEmpty = function(){
return items.length == 0;
}
//移除栈里所有元素
Stack.prototype.clear = function(){
items = [];
}
//返回元素的个数
Stack.prototype.size = function(){
return items.length;
}
//打印栈里的元素
Stack.prototype.print = function(){
console.log(items.toString());
}
}
}
var stack = new Stack();
//入栈5个元素 并打印
stack.push(5);
stack.push(8);
stack.push(1);
stack.push(10);
stack.push(7);
stack.print();              //5,8,1,10,7
//输出栈的大小
console.log(stack.size());  //5
//取出栈顶元素并打印
console.log(stack.peek());  //7
stack.print();              //5,8,1,10,7
//出栈并打印
stack.pop();
stack.print();              //5,8,1,10
//清空栈并判空
stack.clear();
console.log(stack.isEmpty());//true

由上段代码:

(1)使用动态原型模式创建对象

(2)利用数组,和数组的push()和pop()函数实现入栈和出栈。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: