栈是一种高效的数据结构,因为数据只能在栈顶添加或删除,被称为一种后进先出(LIFO)的数据结构。
push():入栈
pop():出栈
peek():只返回栈顶元素,而不删除它
function Stack() {
let items = [];
this.push = element => {
items.push(element);
};
this.pop = () => {
return items.pop();
};
this.peek = () => {
return items[items.length - 1];
};
this.isEmpty = () => {
return items.length == 0;
};
this.size = () => {
return items.length;
};
this.clear = () => {
items = [];
};
this.print = () => {
console.log(items.toString());
};
}
------------------------------------------------------------
// 将数字转换为二进制、八进制以及十六进制
function baseConverter(num, base) {
let remStack = new Stack();
let digits = "0123456789ABCDEF";
let baseStr = "";
while (num > 0) {
remStack.push(Math.floor(num % base));
num = Math.floor(num / base);
}
while( !remStack.isEmpty()) {
baseStr += digits[remStack.pop()];
}
return baseStr;
}
console.log(baseConverter(1100, 2))
console.log(baseConverter(1100, 8))
console.log(baseConverter(1100, 16))
------------------------------------------------------------
// 判断是否回文
function isPalindrome(word){
let s = new Stack();
for(let i=0; i<word.length; ++i){
s.push(word[i]);
}
let rword = "";
while(s.size() > 0){
rword += s.pop();
}
if(rword === word){
return true;
}else{
return false;
}
}
let word = "helleh";
if(isPalindrome(word)){
log(word + " 是回文!");
}else{
log(word + " 不是回文!");
}
------------------------------------------------------------
// 递归
function factorial1(n){
if (n === 0){
return 1;
} else {
return n * factorial1(n - 1);
}
}
function factorial2(n){
let s = new Stack();
while(n > 1){
s.push(n--);
}
let product = 1;
while(s.size() > 0){
product *= s.pop();
}
return product;
}
console.log(factorial1(5));
console.log(factorial2(5));