栈的基本操作
function Stack () {
this.item = [];
Stack.prototype.push = function (val) {
return this.item.push(val);
}
Stack.prototype.pop = function () {
return this.item.pop();
}
// 查看栈顶元素
Stack.prototype.peek = function () {
return this.item[this.item.length - 1];
}
Stack.prototype.isEmpty = function () {
return this.item.length === 0 ? true : false;
}
Stack.prototype.size = function () {
return this.item.length;
}
Stack.prototype.toString = function () {
return this.item.toString();
}
}
let stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
console.log(stack.toString());
stack.pop();
console.log(stack.toString());
console.log(stack.peek());
进制转换
//只能是2,8,16进制转换
let standard = '0123456789ABCDEF';
function transfrom (val, ary) {
let flag = [2, 8, 16].find(item => item == ary)
if (!flag) return false;
let arr = [];
let result = '';
while (val) {
arr.push(val % ary);
val = Math.floor(val / ary);
}
switch (ary) {
case 2: break;
case 8: result += '0'; break;
case 16: result += '0x'; break;
default: return;
}
if (arr.length != 0) {
while (arr.length !== 0) {
if (ary === 16) {
result += standard[arr.pop()]
} else {
result += arr.pop();
}
}
return result;
}
return 0
}
let result = transfrom(0, 16);
console.log(result);
这篇博客介绍了栈数据结构的实现,包括push、pop、peek等基本操作,并通过示例展示了如何使用栈。此外,还讲解了进制转换的方法,特别是从任意数值到2、8、16进制的转换过程。
706

被折叠的 条评论
为什么被折叠?



