-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.js
113 lines (97 loc) · 1.68 KB
/
stack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* 实现栈类Stack
* @time:2017-12-27
* @author:谢海涛
* */
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}
/**
* 入栈
* @param element
*/
function push(element) {
this.dataStore[this.top++] = element;
}
/**
* 出栈
*/
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;
}
// 运用例子1:数制间的相互转换
function mulBase(num, base) {
var s = new Stack();
do {
s.push(num % base)
num = Math.floor(num /= base)
} while (num > 0)
var result = '';
while (s.length() > 0) {
result += s.pop();
}
return result;
}
console.log(mulBase(10, 8))
function factorial(n) {
if (n == 0) {
return 1;
}else{
return n*factorial(n-1)
}
}
console.log(factorial(5))
// 实例运用2:模拟递归
function fact(n) {
var s = new Stack();
while(n>1){
s.push(n--);
}
var result = 1;
while(s.length()>0){
result*=s.pop();
}
return result;
}
console.log(fact(5))
// 实例运用3:回文
function isPalindrome(word) {
var s = new Stack();
for(var i=0;i<word.length;i++){
s.push(word[i]);
}
var newWord = '';
while(s.length()>0){
newWord+=s.pop();
}
if(word==newWord){
return true;
}else{
return false;
}
}
console.log(isPalindrome('racecar'))