JS数据结构之栈

420 阅读1分钟
原文链接: zhuanlan.zhihu.com
/*
 * @desc: 栈:后进先出(LIFO)
 * @举例: 从一摞盘子中按照顺序取走一个盘子, 只能从栈顶取出
 * @feature: 只能在栈顶进行元素的添加与删除。(进栈(入栈)/出栈(弹出栈))
 *
 * @ADT模型
 *
 * top属性: 标记栈顶当前位置(默认0)
 * empty属性: 是否为空栈
 * push(): 入栈
 * pop(): 出栈
 * peek(): 查看栈定元素
 * clear(): 清空栈内元素
 * length(): 获取栈内元素个数和
 */

class Stack {

  constructor() {
    this.top = 0
    this.empty = true
    this.dataStore = []
  }

  push (element) {
    this.dataStore[this.top++] = element
  }

  pop () {
    // 下移栈顶位置
    return this.dataStore[--this.top]
  }

  peek () {
    return this.dataStore[this.top - 1]
  }

  clear () {
    this.top = 0
  }

  length () {
    return this.top
  }

}

module.exports = Stack
实践
  • 将数字转换为二进制和八进制
const Stack = require('./Stack.js')

function mulBase (num, base) {
    let converted = ''
    const stack = new Stack()
    do {
        stack.push( num % base)
        num = Math.floor(num /= base)
    } while (num > 0)
    while (stack.length() > 0) {
        converted += stack.pop()
    }
    return converted
}

console.log('==================')
console.log(mulBase(32, 2)) // '100000'
console.log(mulBase(125, 8))  // '175'
console.log('==================')
  • 判断回文: 一种现象:一个单词、短语或数字,从前往后写和从后往前写都是一样的
const Stack = require('./Stack.js')


function isPalindrome (word) {
    let rword = ''
    const stack = new Stack()
    if (word.length > 0) {
        for (let i = 0; i < word.length; i++) {
            stack.push(word[i])
        }
        while (stack.length() > 0) {
            rword += stack.pop()
        }
        return rword === word ? true : false
    }
    return false
}

console.log('==================')
console.log(isPalindrome('hello')) // false
console.log(isPalindrome('racecar'))  // true
console.log('==================')
  • 栈模拟递归
const Stack = require('./Stack.js')

function factorial (n) {
    const s = new Stack()
    let res = 1
    while (n > 1) {
        s.push(n--)
    }
    while (s.length() > 0) {
        res *= s.pop()
    }
    return res
}

console.log('==================')
console.log(factorial(5)) // 120
console.log('==================')
  • 栈可以用来判断一个算术表达式中的括号是否匹配。编写一个函数,该函数接受一个算术表达式作为参数, 返回括号缺失的位置,下面是一个括号不匹配的算术表达式的例 子:2.3 + 23 / 12 + (3.14159×0.24。
const Stack = require('./Stack.js')


function dictBrackets (expression) {
    const s = new Stack()
    let res = ''
    for (let i = 0; i < expression.length; i++) {
        if (expression[i] === '(') {
            s.push(i)
        } else if (expression[i] === ')') {
            s.pop()
        }
    }
    if (s.length() > 0) {
        return s.peek()
    } else {
        return false
    }
}


console.log('==================')
console.log(dictBrackets('2.3 + 23 / 12 + (3.14159×0.24')) // 16
console.log(dictBrackets('2.3 + 23 / 12 + (3.14159×0.24)')) // false
console.log('==================')