使用JavaScript对栈的实现:

使用JavaScript对栈的实现:
// Stack类
function Stack() {
//用数组dataStore保存栈内元素
this.dataStore = [];
// top记录栈顶的位置初始化为0
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length
}
// 压入新元素,保存到top所对应的位置,然后将top+1,让其指向下一个空位置
function push(element) {
this.dataStore[this.top++] = element
}
// pop()方法与push方法相反,先返回栈顶元素,同时将变量top值减1
function pop() {
return this.dataStore[–this.top]
}
// peek()方法返回数组的第top-1个位置元素,即栈顶元素
function peek() {
return this.dataStore[this.top - 1]
}
// 可以将变量top值为0,轻松制造一个空栈
function clear() {
this.top = 0
}
// length()通过返回top值来决定元素个数
function length() {
return this.top
}
//使用栈来实现数制间转换
function mulBase(num, base) {
var s = new Stack();
do {
s.push(num % base)
num = Math.floor(num /= base)
}
while (num > 0) {
var converted = “”;
while (s.length() > 0) {
converted += s.pop()
}
return converted
}
}
var num = 32;
var base = 2
var newNum = mulBase(32, 2)
console.log(newNum);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值