/**
* Stack 类
*/
class Stack {
constructor() {
this.data = []; // 对数据初始化
this.top = 0; // 初始化栈顶位置
}
// 入栈方法
push() {
const args = [...arguments];
args.forEach(arg => this.data[this.top++] = arg);
return this.top;
}
// 出栈方法
pop() {
if (this.top === 0) throw new Error('The stack is already empty!');
const peek = this.data[--this.top];
this.data = this.data.slice(0, -1);
return peek;
}
// 返回栈顶元素
peek() {
return this.data[this.top - 1];
}
// 返回栈内元素个数
length() {
return this.top;
}
// 清除栈内所有元素
clear() {
this.top = 0;
return this.data = [];
}
// 判断栈是否为空
isEmpty() {
return this.top === 0;
}
}
// 实例化
const stack = new Stack();
stack.push(1);
stack.push(2, 3);
console.log(stack.data); // [1, 2, 3]
console.log(stack.peek()); // 3
console.log(stack.pop()); // 3, now data is [1, 2]
stack.push(3);
console.log(stack.length()); // 3
stack.clear(); // now data is []
/**
* 将数字转换为二进制和八进制
*/
const numConvert = (num, base) => {
const stack = new Stack();
let converted = '';
while(num > 0) {
stack.push(num % base);
num = Math.floor(num / base);
}
while(stack.length() > 0) {
converted += stack.pop();
}
return +converted;
}
console.log(numConvert(10, 2)); // 1010
/**
* 判断给定字符串或者数字是否是回文
*/
const isPalindrome = words => {
const stack = new Stack();
let wordsCopy = '';
words = words.toString();
Array.prototype.forEach.call(words, word => stack.push(word));
while(stack.length() > 0) {
wordsCopy += stack.pop();
}
return words === wordsCopy;
}
console.log(isPalindrome('1a121a1')); // true
console.log(isPalindrome(2121)); // false
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有