更详尽参看:
4️⃣ 栈

利用数组实现

  1. class StackArray {
  2. constructor() {
  3. this.items = []
  4. }
  5. push(elem) {
  6. this.items.push(elem)
  7. }
  8. pop() {
  9. if (this.isEmpty()) {
  10. return undefined
  11. }
  12. return this.items.pop()
  13. }
  14. isEmpty() {
  15. return this.items.length === 0
  16. }
  17. peek() {
  18. if (this.isEmpty()) {
  19. return undefined
  20. }
  21. return this.items[this.items.length - 1]
  22. }
  23. size() {
  24. return this.items.length
  25. }
  26. clear() {
  27. this.items = []
  28. }
  29. toString() {
  30. let objString = ''
  31. return this.items.reduce((prev,cur,index)=> {
  32. if (index === this.items.length - 1) {
  33. return prev+cur
  34. }
  35. return prev+cur+','
  36. },'')
  37. }
  38. }
  39. let s = new StackArray()
  40. s.push(1)
  41. s.push(2)
  42. s.push('1111')
  43. console.log(s)
  44. console.log(s.toString())
  45. s.pop()
  46. console.log(s.size())
  47. console.log(s.peek())
  48. s.clear()
  49. console.log(s)
  50. console.log(s.size())
  51. console.log(s.peek())
  52. // 输出
  53. // StackArray { items: [ 1, 2, '1111' ] }
  54. // 1,2,1111
  55. // 2
  56. // 2
  57. // StackArray { items: [] }
  58. // 0
  59. // undefined

利用对象实现

  1. class Stack {
  2. constructor() {
  3. this.count = 0
  4. this.items = {}
  5. }
  6. push(elem) {
  7. this.items[this.count] = elem
  8. this.count++
  9. }
  10. pop() {
  11. if (this.isEmpty()) {
  12. return undefined
  13. }
  14. this.count--
  15. const result = this.items[this.count]
  16. delete this.items[this.count]
  17. return result
  18. }
  19. peek() {
  20. if (this.isEmpty()) {
  21. return undefined
  22. }
  23. return this.items[this.count - 1]
  24. }
  25. isEmpty() {
  26. return this.count === 0
  27. }
  28. size() {
  29. return this.count
  30. }
  31. clear() {
  32. this.items = {}
  33. this.count = 0
  34. }
  35. toString() {
  36. if (this.isEmpty()) {
  37. return ''
  38. }
  39. let objString = `${this.items[0]}`
  40. for(let i=1;i<this.count;i++){
  41. objString += `,${this.items[i]}`
  42. }
  43. return objString
  44. }
  45. }
  46. let s = new Stack()
  47. s.push(1)
  48. s.push(2)
  49. s.push('1111')
  50. console.log(s)
  51. console.log(s.toString())
  52. s.pop()
  53. console.log(s.size())
  54. console.log(s.peek())
  55. s.clear()
  56. console.log(s)
  57. console.log(s.size())
  58. console.log(s.peek())
  59. // 输出
  60. // Stack { count: 3, items: { '0': 1, '1': 2, '2': '1111' } }
  61. // 1,2,1111
  62. // 2
  63. // 2
  64. // Stack { count: 0, items: {} }
  65. // 0
  66. // undefined