栈(stack)

function Stack(){
	var items = [];
	//进栈
	this.push = function(element){
		items.push(element);
	}
	//出栈
	this.pop = function(){
		return items.pop();
	}
	//栈的长度
	this.size = function(){
		return items.length;
	}
	//是否为空
	this.isEmpty = function(){
		return items.length == 0;
	}
	//清除
	this.clear = function(){
		items = [];
	}
	//获得栈顶元素
	this.peek = function(){
		return items[items.length -1];
	}
	//打印栈
	this.print = function(){
		console.log(items);
	}
}

var stack = new Stack();
console.log(stack.isEmpty());//true
stack.push('apple');
console.log(stack.size());//1
console.log(stack.isEmpty());//false
console.log(stack.peek())//apple
stack.print();//[ 'apple' ]
stack.clear();//
stack.print();//[]
posted @ 2018-01-04 13:47  IT-caijw  阅读(152)  评论(0编辑  收藏  举报