javascript数据结构之栈

function stack() {
	this.data = [];
	this.top = 0;
	this.push = push;
	this.pop = pop;
	this.clear = clear;
	this.length = length;
}

function push(element) {
	this.data[this.top++] = element;
}

function pop(element) {
	this.data[--this.top];
}

function clear() {
	this.top = 0;
	this.data = [];
}

function length() {
	return this.top;
}

/*
 * 
 * 可以利用栈将一个数字从一种数制转换成另一种数制。假设想将数字n 转换为以b 为基数 的数字,实现转换的算法如下。 (1) 最高位为n %
 * b,将此位压入栈。 (2) 使用n/b 代替n。 (3) 重复步骤1 和2,直到n 等于0,且没有余数。 (4)
 * 持续将栈内元素弹出,直到栈为空,依次将这些元素排列,就得到转换后数字的字符串形式。
 * 
 */

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;
}

num = 125;
base = 8;
var newNum = mulBase(num, base);
print(num + " converted to base " + base + " is " + newNum);

// 判断给定字符串是否是回文
function isPalindrome(word) {
	var s = new Stack();
	for (var i = 0; i < word.length; ++i) {
		s.push(word[i]);
	}
	var rword = "";
	while (s.length() > 0) {
		rword += s.pop();
	}
	if (word == rword) {
		return true;
	} else {
		return false;
	}
}
var word = "hello";
if (isPalindrome(word)) {
	print(word + " is a palindrome.");
} else {
	print(word + " is not a palindrome.");
}
word = "racecar"
if (isPalindrome(word)) {
	print(word + " is a palindrome.");
} else {
	print(word + " is not a palindrome.");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值