构造函数:
function Stack () {
this.dataStore = [];
this.top =0;
this.push =push;
this.pop =pop;
this.peek =peek;
this.clear =clear;
this.length =length;
}
push:
function push (element) {
this.dataStore[this.top++] =element;
}
pop:
function pop(){
return this.dataStore[--this.top]; /* 这个函数始终看不懂,为什么不是返回this.top 而是自减一个1 这样返回的难道不是栈顶下的第一个元素吗*/
}
因为push的时候是先给this.top
的位置赋上element
的值,然后才自加,top
指的是下一位置的指针,所以pop的时候是要先自减。
都被你带跑偏了,假如栈内有三个元素,你一个个压栈出栈看看
var a = new Stack();
a.push(111);
console.log(a.top);//此处输出为 1, 刚才push进去的那个元素是保存在下标为 0 的位置上, 所以在pop的时候,要先减 top 值,然后再返回对应的那个.
top
记录着下一次 push
时, 元素要保存的位置, 所以当要 pop
时, 需要先减1, 以指向最后一个元素.
stack为后进先出
初始化的时候top值为0
那么你push的时候
function push (element) {
this.dataStore[this.top++] =element;
}
++操作符后置
等价为
function push (element) {
this.dataStore[this.top] =element;
this.top=this.top+1;
}
添加完一个元素后,top值为1
那么pop操作为从尾部弹出最后一个元素
function pop(){
return this.dataStore[--this.top];
}
--操作符前置
等价为
function pop(){
this.top=this.top-1;
return this.dataStore[this.top];
}
top值为0,就是弹出刚添加的元素
如果top为N
那么push完了后top值为N+1
pop完了后 top为N-1
top的值始终和stackpush/pop完了后元素的长度保持一致
top>=0
首先你要定义好top
的含义:
表示当前栈顶元素的位置
表示将要入栈的下一个元素的位置
很明显你的代码是第二种含义。