1:概念

栈是一种遵从后进先出(LIFO)原则的有序集合,新添加的或待删除的元素都保存在栈的末尾.

在栈里面新元素都靠近栈顶,旧元素都接近栈低.

2.栈的创建

function Stack(){

  //各种属性和方法的声明

}

首先我们需要一种数据结构开保存栈里面的元素,可以选择数组

var items=[];

栈api:

push(element)(添加一个或者几个元素到栈顶);pop()移除栈顶的元素,同时返回被删除新的元素.

peek()返回栈顶元素,不对栈做任何修改(这个方法不会移除栈顶的元素,仅仅返回它);isEmpty()(如果栈中没有任何元素就返回true,否则就返回false)

clear():移除栈中的所有的元素size()返回栈中的元素的个数.

栈完整的代码:

function Stack(){
	var item = [];
	this.push = function(element){
		item.push(element);
	}
	this.pop = function(){
		return item.pop();
	}
	this.peek = function(){
		return item[item.length-1];
	}
	this.isEmpty = function(){
		return item.length == 0;
	}
	this.size = function(){
		return item.length;
	}
	this.clear = function(){
		item = [];
	}
	this.print = function(){
		console.log(item.toString());
	}
}

  

原文地址:https://www.cnblogs.com/airycode/p/8074294.html