1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title></title>
6 </head>
7 <body>
8 <script>
9 function Stack(){
10 this.arr = [];
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(ele){
19 this.arr[this.top++] = ele;
20 }
21
22 function pop(){
23 var value = this.arr[this.top-1];
24 this.arr.pop();
25 this.top--;
26 return value;
27 }
28
29 function peek(){
30 return this.arr[this.top-1];
31 }
32 function length(){
33 return this.top;
34 }
35 function clear(){
36 this.top = 0;
37 this.arr = [];
38 }
39
40
41
42
43
44 var s = new Stack();
45 s.push("zhangsan");
46 s.push("lisi");
47 s.push("wangwu");
48 s.push("zhaoliu");
49
50 console.log(s.length());
51 console.log(s.pop());
52 console.log(s.arr);
53 console.log(s.peek());
54 console.log(s.arr);
55 s.clear();
56 console.log(s.arr);
57
58
59 // 应用 将数字转换为二到九进制: 无法转换16进制
60 function mulBase(num,base){
61 var s = new Stack();
62 do{
63 s.push(num%base);
64 num = Math.floor(num /= base);
65 }while (num>0);
66
67 var converted = '';
68 while(s.length() > 0 ){
69 converted += s.pop();
70 }
71 return converted;
72 }
73
74 console.log(mulBase(11,3));
75
76
77 //判断字符串回文
78 function isPalindrome(word){
79 var s = new Stack();
80 for(var i=0;i<word.length;i++){
81 s.push(word[i]);
82 }
83 var rword ='';
84 while(s.length()>0){
85 rword += s.pop();
86 }
87 return word == rword;
88 }
89
90 console.log(isPalindrome("hello"));
91 console.log(isPalindrome("elle"));
92
93
94 //使用栈模拟递归
95 function fact(n){
96 var s = new Stack();
97 while(n>1){
98 s.push(n--);
99 }
100 var product = 1;
101 while(s.length() >0 ){
102 product *=s.pop();
103 }
104 return product;
105 }
106
107 console.log(fact(5));
108 </script>
109 </body>
110 </html>