栈是一种支持后进先出(LIFO)的集合,即后被插入的数据,先被取出,栈的示意图如图1。
图1
首先声明构造函数Stack,里面定义我们需要的属性和方法,代码如下。
function Stack(){
//用于储存栈元素的数组
this.dataStore = [];
//记录dataStore中元素的个数,由于数组的下标是从0开始的,所以相当于指向栈中顶部元素下标+1的位置,也可以理解为指向下一个入栈元素的下标位置。
this.top =0;
//入栈方法
this.push = push;
//出栈方法
this.pop = pop;
//返回顶部的栈元素
this.peek = peek;
//清除栈元素
this.clear = clear;
//返回栈元素个数
this.length = length;
}
push方法实现
栈中向top位置插入元素后,top值更新,元素个数+1。
function push (element) {
this.dataStore[this.top++] = element;
}
pop方法实现
元素出栈,top值减1,指向当前栈顶元素下标位置,删除该元素作为出栈操作。
function pop() {
var topvalue = this.dataStore[--this.top];
delete this.dataStore[this.top];
return topvalue;
}
peek方法实现
peek方法返回顶部的栈元素,即取dataStore的最后一个位置的值,也就是dataStore下标为top-1的值,
function peek() {
return this.dataStore[this.top-1];
}
clear方法实现
clear 方法清除栈内元素,把栈的长度重置为0,另外还要把dataStore数组置空,因为数组中的元素始终被dataStore引用,导致垃圾回收器无法将其回收,从而造成内存浪费。
function clear () {
this.top = 0;
//下面两句任选其一清除数组dataStore里的数据
// this.dataStore = [];
this.dataStore.length = 0;
}
length 方法实现
length 方法获取栈中的元素个数top,
function length() {
return this.top;
}
下面写段代码测试一下;
var a = new Stack();
a.push(1);
a.push(2);
a.push(3);
console.log("开始的dataStore为:"+a.dataStore+" 栈的长度为:"+a.length()); //输出:开始的dataStore为:1,2,3 栈的长度为:3
a.pop();
console.log("出栈一个值后dataStore为:"+a.dataStore+" 栈的长度为:"+a.length()); //输出:出栈一个值后dataStore为:1,2, 栈的长度为:2
a.clear();
console.log("清除栈后dataStore为:"+a.dataStore+" 栈的长度为:"+a.length()); //输出:清除栈后dataStore为: 栈的长度为:0
需要完整的代码请到 https://github.com/lilythy/dataStructure/blob/master/stack.html 查看。