1.对栈的操作
- 栈是一种后入先出的数据结构。
- push()入栈
- pop()出栈
- peek()返回栈顶元素
- clear()清除栈内所有元素
- length 记录栈内元素个数
2.栈的实现
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 clear () {
this.top = 0
}
// 栈元素个数
function length () {
return this.top
}
}
let s = new Stack()
s.push('wayliu')
s.push('liuguowei')
console.log(s.length()) // 2
console.log(s.peek()) // liuguowei
s.pop()
console.log(s.length()) // 1
只是通过top来标记栈的元素与栈顶,但是存储的数组dataStore里的值没有改变。
3.数制间相互转换
将数字n换成以b为基数的数字
- 最高位为 n % b,将此位入栈。
- 使用 n/b 代替 n。
- 重复步骤1 和 2,直到n等于0且没有余数
- 持续将栈内元素弹出,直到栈为空,依次将这些元素排列,就得到转换后数组的字符串形式。
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
}
console.log(mulBase(8,2)) // 1000
可以使用数组模拟栈
function mulBase (num,base) {
var s = new Array() // 使用数组模拟栈
do {
s.push(num % base)
num = Math.floor(num /= base)
} while (num > 0)
var converted = ""
while (s.length > 0) {
converted += s.pop()
}
return converted
}
console.log(mulBase(8,2)) // 1000
4.回文
什么是回文?
回文是指这样一种现象:一个单词、短语或数字,从前往后写和从后往前写都是一样的。 比如,单词“dad”、“racecar”就是回文;如果忽略空格和标点符号,下面这个句子也是回 文,“A man, a plan, a canal: Panama”;数字 1001 也是回文。
判断回文
- 使用栈可以轻松判断回文。
- 把字符串的每个字符从左到右顺序入栈,当字符串中的字符都入栈后,栈内就保存了一个反转后的字符串。
- 把栈内字符串出栈与原字符串比较即可。
使用前面定义的栈类判断
function isPalindrome(world) {
let s = new Stack()
for (let i = 0; i <world.length; i++) {
s.push(world[i])
}
let rworld = ""
while (s.length() > 0) {
rworld += s.pop()
}
if (world === rworld) {
return true
} else {
return false
}
}
console.log(isPalindrome('abccba')) // true
同样的可以用数组模拟
function isPalindrome(world) {
let s = new Array()
for (let i = 0; i <world.length; i++) {
s.push(world[i])
}
let rworld = ""
while (s.length > 0) {
rworld += s.pop()
}
if (world === rworld) {
return true
} else {
return false
}
}
console.log(isPalindrome('abccba')) //true
5.使用栈模拟递归过程
function fact (n) {
let s = new Array()
while (n > 1) {
s.push(n)
}
let product = 1
while (s.length > 0) {
product *= s.pop()
}
return product
}
6.练习题
- 栈可以用来判断一个算术表达式中的括号是否匹配。编写一个函数,该函数接受一个算 术表达式作为参数,返回括号缺失的位置。下面是一个括号不匹配的算术表达式的例 子:2.3 + 23 / 12 + (3.14159×0.24。
function findWrongBrace (express) {
let s = new Stack();
for (let i = 0; i < express.length; ++i) {
if (express[i] === `(`) {
s.push(i);
} else if (express[i] === `)`) {
s.pop();
}
}
return `${express}的第${s.peek() + 1}个字符是不匹配的括号。`;
}
console.log(findWrongBrace(`2.3 + 23 / 12 + (3.14159 * 0.24`));
// 2.3 + 23 / 12 + (3.14159 * 0.24的第17个字符是不匹配的括号。