/*鏈棧的JS實現(xiàn)*/
function LinkedStack(){
//節(jié)點結(jié)構(gòu)定義
var Node = function(element){
this.element = element;
this.next = null;
}
var length = 0,
top; //棧頂指針
//壓棧操作
this.push = function(element){
var node = new Node(element),
current;
if(!top){
top = node;
length++;
return true;
}else{
node.next = top;
top = node;
length++;
return true;
}
}
//退棧操作
this.pop = function(){
var current = top;
if(top){
top = current.next;
current.next = null;
length--;
return current;
}else{
return 'null stack';
}
}
//獲取棧頂節(jié)點
this.top = function(){
return top;
}
//獲取棧長
this.size = function(){
return length;
}
this.toString = function(){
var string = '',
current = top;
while(current){
string += current.element;
current = current.next;
}
return string;
}
//清空棧
this.clear = function(){
top = null;
length = 0;
return true;
}
}
//順序棧的JS實現(xiàn) 這里直接使用了JS內(nèi)置的Array對象
function ArrayStack(){
var arr = [];
//壓棧操作
this.push = function(element){
arr.push(element);
}
//退棧操作
this.pop = function(){
return arr.pop();
}
//獲取棧頂元素
this.top = function(){
return arr[arr.length-1];
}
//獲取棧長
this.size = function(){
return arr.length;
}
//清空棧
this.clear = function(){
arr = [];
return true;
}
this.toString = function(){
return arr.toString();
}
}
參考鏈接:棧的JS實現(xiàn)