function Stack() {
this.dataStore = []
this.top = 0//栈顶,会变化
this.push = push
this.pop = pop
this.peek = peek//栈顶
this.clear = clear
this.length = length
}
function push(element) {
this.dataStore[this.top++] = element
}
function pop() {
return this.dataStore[--this.top]
}
function peek() {
return this.dataStore[this.top - 1]
}
function length() {
return this.top
}
function clear() {
this.top = 0
}
var s = new Stack()
s.push('aa')
s.push('bb')
s.push('cc')
s.push('dd')
console.log('length:' + s.length())
console.log(s.peek())
var popped = s.pop()
console.log('the popped element is:' + popped)
console.log(s.peek())
s.push('ee')
console.log(s.peek())
s.clear()
console.log('length:' + s.length())
console.log(s.peek())
s.push('ff')
console.log(s.peek())
/*
数制间的相互转换
可以利用栈将一个数字从一种数制转换成另一种数制。假设想将数字 n 转换为以 b 为基数的数字
eg:将十进制16转化为二进制,n = 16,b = 2;
(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
}
//将数字转化为二进制和八进制
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(num, base)
console.log(num + " converted to base " + base + " is " + newNum)
var num = 125
base = 8
var newNum = mulBase(num, base)
console.log(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)) {
console.log(word + " is a palindrome.")
} else {
console.log(word + " is not a palindrome.")
}
word = 'racecar'
if (isPalindrome(word)) {
console.log(word + " is a palindrome.")
} else {
console.log(word + " is not a palindrome.")
}
// 5! = 5x4x3x2x1 = 120
function factorial(n) {
if (n === 0) {
return 1
} else {
return n * factorial(n - 1)
}
}
//使用栈模拟递归过程
function fact(n) {
var s = new Stack()
while (n > 1) {
s.push(n--)
}
var product = 1
while (s.length() > 0) {
product *= s.pop()
}
return product
}
console.log(factorial(5))
栈
最新推荐文章于 2024-09-17 13:08:54 发布