美文网首页前端大杂烩
数据结构 — 堆栈

数据结构 — 堆栈

作者: lio_zero | 来源:发表于2022-05-29 10:50 被阅读0次

    堆栈(Stack)是一种线性数据结构,其行为类似于现实世界中的项目堆栈。它遵循后进先出(LIFO)的操作顺序,类似于现实世界中的对应物。这意味着新项目将添加到堆栈顶部,项目也将从堆栈顶部移除。

    JavaScript 堆栈可视化

    栈数据结构的主要操作有:

    • push:将元素添加到堆栈顶部
    • pop:从堆栈顶部移除元素
    • peek:检索堆栈顶部的元素,而不删除它
    • isEmpty:检查堆栈是否为空

    JavaScript 实现

    class Stack {
      constructor() {
        this.items = []
      }
    
      push(item) {
        this.items.unshift(item)
      }
    
      pop(item) {
        return this.items.shift()
      }
    
      peek(item) {
        return this.items[0]
      }
    
      isEmpty() {
        return this.items.length === 0
      }
    }
    
    • 使用 constructor 创建一个类(class),为每个实例初始化空数组 items
    • 定义一个 push() 方法,使用 Array.prototype.unshift() 将元素添加到 items 数组的末尾。
    • 定义一个 pop() 方法,使用 Array.prototype.shift()items 数组的开头删除元素。
    • 定义一个 peek() 方法,检索 items 数组中第一个元素的值,而不删除它。
    • 定义一个 isEmpty() 方法,使用 Array.prototype.length 判断 items 数组是否为空。
    const stack = new Stack()
    
    stack.push('apples')
    stack.push('oranges')
    stack.push('pears')
    
    stack.isEmpty() // false
    
    stack.peek() // 'pears'
    
    stack.pop() // 'pears'
    stack.pop() // 'oranges'
    stack.pop() // 'apples'
    
    stack.isEmpty() // true
    

    以上内容来自 30 seconds of code 的 JavaScript Data Structures - Stack

    Leetcode 相关的堆栈题目

    最小栈

    更多资料

    Stack

    相关文章

      网友评论

        本文标题:数据结构 — 堆栈

        本文链接:https://www.haomeiwen.com/subject/pfyiprtx.html