Fork me on GitHub

javascript数据结构-栈

github博客地址

栈(stack)又名堆栈,它是一种运算受限的线性表。遵循后进先出原则,像垃圾桶似的。
功能实现依然按照增删改查来进行,内部数据存储可以借用语言原生支持的数组。

栈类

function Stack(){
	this.data = [];
}

  

添加数据

数据添加到末尾

push: function (element){
	this.data.push(element);
}

  

删除数据

从末尾删除

pop: function (){
	this.data.pop();
}

  

获取数据

返回最后一个添加的

peek: function (){
	return this.data[this.size() - 1];
}

  

是否为空

isEmpty: function (){
	return this.data.length == 0;
}

  

清空数据

clear: function (){
	this.data= [];
}

  

数据长度

size: function (){
	return this.data.length;
}

  

辅助函数,打印数据

print: function (){
	console.log(this.data.toString());
}

  

完整代码

 1 function Stack(){
 2     this.data = [];
 3 }
 4 Stack.prototype = {
 5     push: function (element){
 6         this.data.push(element);
 7     },
 8     pop: function (){
 9         this.data.pop();
10     },
11     peek: function (){
12         return this.data[this.data.length - 1];
13     },
14     isEmpty: function (){
15         return this.data.length == 0;
16     },
17     clear: function (){
18         this.data= [];
19     },
20     size: function (){
21         return this.data.length;
22     },
23     print: function (){
24         console.log(this.data.toString());
25     }
26 }
View Code

 

posted @ 2016-11-08 15:48  donglegend  阅读(155)  评论(0编辑  收藏  举报