当前位置:首页 > JavaScript

js 堆栈实现

2026-01-30 13:12:10JavaScript

堆栈的基本概念

堆栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构。主要操作包括压栈(push)和弹栈(pop),其他常见操作有查看栈顶元素(peek)和判断栈是否为空(isEmpty)。

使用数组实现堆栈

数组是实现堆栈的简单方式,通过维护一个指针(通常称为top)来跟踪栈顶位置。

js 堆栈实现

class Stack {
  constructor() {
    this.items = [];
    this.top = -1; // 初始状态下栈为空
  }

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

  pop() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    const poppedItem = this.items[this.top];
    this.top--;
    return poppedItem;
  }

  peek() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    return this.items[this.top];
  }

  isEmpty() {
    return this.top === -1;
  }

  size() {
    return this.top + 1;
  }

  clear() {
    this.items = [];
    this.top = -1;
  }
}

使用链表实现堆栈

链表实现堆栈更灵活,动态内存分配避免了数组的固定大小限制。

js 堆栈实现

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedListStack {
  constructor() {
    this.top = null;
    this.length = 0;
  }

  push(value) {
    const newNode = new Node(value);
    newNode.next = this.top;
    this.top = newNode;
    this.length++;
  }

  pop() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    const poppedNode = this.top;
    this.top = this.top.next;
    this.length--;
    return poppedNode.value;
  }

  peek() {
    if (this.isEmpty()) {
      return "Stack is empty";
    }
    return this.top.value;
  }

  isEmpty() {
    return this.top === null;
  }

  size() {
    return this.length;
  }

  clear() {
    this.top = null;
    this.length = 0;
  }
}

堆栈的应用场景

堆栈常用于需要回溯或反转的场景,例如:

  • 函数调用栈:记录函数的调用顺序。
  • 括号匹配:检查表达式中的括号是否成对。
  • 撤销操作:保存操作历史以便回退。

示例:括号匹配

使用堆栈检查字符串中的括号是否匹配:

function isBalanced(expression) {
  const stack = new Stack();
  const brackets = { '(': ')', '[': ']', '{': '}' };

  for (let char of expression) {
    if (brackets[char]) {
      stack.push(char);
    } else if (char === ')' || char === ']' || char === '}') {
      if (stack.isEmpty() || brackets[stack.pop()] !== char) {
        return false;
      }
    }
  }

  return stack.isEmpty();
}

console.log(isBalanced("({[]})")); // true
console.log(isBalanced("({[})"));  // false

性能分析

  • 数组实现:访问速度快,但大小固定(动态数组可能涉及扩容开销)。
  • 链表实现:动态大小,但每次操作需处理指针,内存开销略高。

选择实现方式时需根据具体场景权衡。

标签: 堆栈js
分享给朋友:

相关文章

js 实现vue模板

js 实现vue模板

实现 Vue 模板的 JavaScript 方法 通过原生 JavaScript 可以实现类似 Vue 的模板渲染功能,主要包括数据绑定、指令处理和模板解析。以下是核心实现思路: 数据绑定与…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…