《数据结构与算法JavaScript描述》
第4章 栈(Stack)
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <script> 9 function Stack () { 10 this.dataStore = []; 11 this.top = 0; 12 this.push = push; 13 this.pop = pop; 14 this.peek = peek; 15 this.length = length; 16 this.clear = clear; 17 } 18 function push (element) { 19 this.dataStore[this.top++] = element; 20 } 21 function pop () { 22 var popped = this.dataStore[--this.top]; 23 this.dataStore.length = this.top; 24 return popped; 25 } 26 function peek () { 27 return this.dataStore[this.top-1]; 28 } 29 function length () { 30 return this.top; 31 } 32 function clear () { 33 this.top = 0; 34 delete this.dataStore; 35 this.dataStore = []; 36 } 37 function mulBase(num,base) { 38 var s = new Stack(); 39 do { 40 s.push(num % base); 41 num = Math.floor(num /= base); 42 } while (num > 0) { 43 var converted = ‘‘; 44 while ( s.length() > 0 ) { 45 converted += s.pop(); 46 } 47 return converted; 48 } 49 } 50 function factorial(n) { 51 if (n === 0) { 52 return 1; 53 } else { 54 return n * arguments.callee(n-1); 55 } 56 } 57 function fact(n) { 58 var s = new Stack(); 59 while (n > 1) { 60 s.push(n--); 61 } 62 var product = 1; 63 while (s.length() > 0) { 64 product *= s.pop(); 65 } 66 return product; 67 } 68 function myFactorial(n) { 69 var dataStore = []; 70 for ( var i = 1; i <= n; i++) { 71 dataStore.push(i); 72 } 73 var product = 1; 74 while (dataStore.length>0) { 75 product *= dataStore.pop(); 76 } 77 return product; 78 } 79 console.log(factorial(5)); 80 console.log(fact(5)); 81 console.log(myFactorial(5)); 82 </script> 83 </body> 84 </html>
50行~78行
使用栈实现阶乘函数的递归,前两种是书中的提供的函数,第三种是自己根据理解修改的函数。
时间: 2024-10-03 13:38:48