js 实现栈

时间:2023-03-08 20:50:29
 function Stack() {
this.dataStore = [];
this.top = 0;
this.push=push;
this.pop=pop;
this.peek=peek;
this.length=length;
this.clear=clear;
} // 入栈
function push(item) {
this.dataStore[this.top++]=(item);
}
// 出栈,返回栈顶元素,并且将元素的栈顶位置-1
function pop() {
return this.dataStore[this.top--]
}
// 预览顶端元素
function peek(){
return this.dataStore[this.top-1];
}
// 返回栈的长度
function length(){
return this.top;
}
// 清空栈
function clear(){
this.top = 0;
}
 //栈的应用实例:
//num要转换的数字 base 要转换为几进制
function convertNum(num,base){
var s=new Stack()
while(num>0){
console.log(num);
s.push(num%base);
num= Math.floor(num/=base);
}
var res="";
while(s.length()>0){
res+=s.pop();
}
return res;
}