1 function Stack() { 2 this.dataStore = []; 3 this.top = 0; 4 this.push=push; 5 this.pop=pop; 6 this.peek=peek; 7 this.length=length; 8 this.clear=clear; 9 } 10 11 // 入栈 12 function push(item) { 13 this.dataStore[this.top++]=(item); 14 } 15 // 出栈,返回栈顶元素,并且将元素的栈顶位置-1 16 function pop() { 17 return this.dataStore[this.top--] 18 } 19 // 预览顶端元素 20 function peek(){ 21 return this.dataStore[this.top-1]; 22 } 23 // 返回栈的长度 24 function length(){ 25 return this.top; 26 } 27 // 清空栈 28 function clear(){ 29 this.top = 0; 30 }
1 //栈的应用实例: 2 //num要转换的数字 base 要转换为几进制 3 function convertNum(num,base){ 4 var s=new Stack() 5 while(num>0){ 6 console.log(num); 7 s.push(num%base); 8 num= Math.floor(num/=base); 9 } 10 var res=""; 11 while(s.length()>0){ 12 res+=s.pop(); 13 } 14 return res; 15 }