栈是一种特殊的列表,栈内的元素只能通过栈顶访问,栈被称为一种后入先出的数据结构。
栈的实现
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 peek() {
return this.dataStore[this.top - 1];
}
// 返回栈顶元素,同时变量top的值减1
function pop() {
return this.dataStore[--this.top];
}
// 清空一个栈
function clear() {
this.top = 0;
}
// 返回栈的长度
function length() {
return this.top;
}
使用Stack类实际例子
将数字转换为二进制和八进制
//只针对2~9的情况
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);//32 converted to base 2 is100000
num = 125;
base = 8;
var newNum = mulBase(num, base);
console.log(num + " converted to base " + base + " is" + newNum);//125 converted to base 8 is175
判断字符串是否是回文
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")
}
//hello is not a palindrome
word = "racecar";
if (isPalindrome(word)) {
console.log(word + " is a palindrome");
} else {
console.log(word + " is not a palindrome")
}
//racecar is a palindrome
使用栈模拟递归过程
先用递归函数实现阶乘:
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));//120
console.log(fact(5));//120