使用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);
使用JavaScript对栈的实现:
最新推荐文章于 2024-08-11 18:40:36 发布