栈是只允许在表尾进行插入,删除的线性表。特点后进先出。
下面将演示用数组实现的栈
栈初始化:创建一个空栈
Init:function(){this.STACKMAX = 100;this.stack = new Array(this.STACKMACK);this.top = -1;return this.stack; }
判断栈空: 若栈为空返回true,否则返回false
Empty:function(){if(this.top==-1){return true;}else{return false;} }
进栈:若栈满,返回“栈满”。否则将元素elem作为新的栈顶元素。
Push:function(elem){if(this.top==this.STACKMAX-1){return "栈满";}else{this.top++;this.stack[this.top] = elem;}}
退栈:删除栈顶元素,并返回其值
Pop:function(){if(this.top==-1){return "空栈,无法删除栈顶元素!";}else{var x = this.stack[this.top];this.top--;return x;}}
读栈顶元素:返回栈顶元素
Top:function(){if(this.top!=-1){return this.stack[this.top];}else{return "空栈,顶元素无返回值!";}}
清空栈:将栈清空为空栈
Clear:function(){this.top=-1; }
栈长度:返回栈的元素个数,既栈的长度
Length:function(){return this.top+1; }
栈示例代码如下:
var Stack = function(){}Stack.prototype={Init:function(){this.STACKMAX = 100;this.stack = new Array(this.STACKMACK);this.top = -1;return this.stack;},Empty:function(){if(this.top==-1){return true;}else{return false;}},Push:function(elem){if(this.top==this.STACKMAX-1){return "栈满";}else{this.top++;this.stack[this.top] = elem;}},Pop:function(){if(this.top==-1){return "空栈,无法删除栈顶元素!";}else{var x = this.stack[this.top];this.top--;return x;}},Top:function(){if(this.top!=-1){return this.stack[this.top];}else{return "空栈,顶元素无返回值!";}},Clear:function(){this.top=-1;},Length:function(){return this.top+1;}}
在最近的日子里会给出栈的应用的例子,在此敬请期待。。。