概念

栈是一种特殊的高效的数据结构
数据只能在栈顶删除或者增加

定义

栈内元素只能通过一端访问,即栈顶、栈底
栈被称为一种后入先出 LIFO 的数据结构
进栈、入栈、压栈
出栈、退栈

代码实现

  1. function Stack() {
  2. this.stackStore = []
  3. this.top = 0
  4. this.push = push
  5. this.pop = pop
  6. this.peek = peek
  7. this.clear = clear
  8. this.getLength = getLength
  9. }
  10. function push(ele) {
  11. this.stackStore[this.top++] = ele
  12. }
  13. function pop() {
  14. if (this.top === 0) return null
  15. // 第一次实现,下面写成了这样子,导致pop为undefined
  16. // return this.stackStore[this.top--]
  17. // 然后改成了这个样子
  18. // return this.stackStore[this.top-- - 1]
  19. // 然后看了一下实现,改成这样子更符合人类思维一点= =
  20. return this.stackStore[--this.top]
  21. }
  22. function peek() {
  23. return this.stackStore[this.top - 1]
  24. }
  25. function clear() {
  26. this.top = 0
  27. this.stackStore = []
  28. }
  29. function getLength() {
  30. return this.top
  31. }
  32. var s = new Stack(),
  33. log = console.log,
  34. warn = console.warn
  35. s.push('n1')
  36. s.push('n2')
  37. s.push('n3')
  38. log(s.peek())
  39. log(s.getLength())
  40. log(s.pop())
  41. log(s.peek())
  42. // 回文算法
  43. function checkHuiWen(str) {
  44. if (!str || typeof str !== 'string') return false
  45. let stack = new Stack(),
  46. res = ''
  47. for (let i = 0; i < str.length; i++) {
  48. stack.push(str[i])
  49. }
  50. while(stack.top != 0) {
  51. res += stack.pop()
  52. }
  53. console.log(res)
  54. if (res === str) {
  55. return true
  56. }
  57. return false
  58. }
  59. warn(checkHuiWen('啊撒旦风口浪尖阿斯顿发链接'))

作用

回文算法,里面用栈存储并退栈拼接