当前位置:首页 > JavaScript

js 实现堆栈

2026-02-01 23:51:36JavaScript

使用数组实现堆栈

在JavaScript中,数组天然支持堆栈的pushpop操作,可以直接模拟堆栈行为。

const stack = [];
stack.push(1); // 入栈
stack.push(2);
const top = stack.pop(); // 出栈,返回2

封装类实现堆栈

通过类封装可以更规范地实现堆栈操作,包括pushpoppeekisEmpty等方法。

js 实现堆栈

class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    if (this.isEmpty()) return undefined;
    return this.items.pop();
  }

  peek() {
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }

  size() {
    return this.items.length;
  }

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

// 使用示例
const stack = new Stack();
stack.push(10);
stack.push(20);
console.log(stack.pop()); // 20

使用链表实现堆栈

链表实现可以避免数组扩容带来的性能问题,适合动态大小堆栈。

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 null;
    const value = this.top.value;
    this.top = this.top.next;
    this.length--;
    return value;
  }

  peek() {
    if (this.isEmpty()) return null;
    return this.top.value;
  }

  isEmpty() {
    return this.length === 0;
  }

  size() {
    return this.length;
  }
}

处理堆栈溢出

JavaScript引擎有调用堆栈大小限制,递归过深会导致堆栈溢出错误。可以通过尾递归优化或改用循环避免。

// 危险示例:可能堆栈溢出
function factorial(n) {
  if (n === 1) return 1;
  return n * factorial(n - 1);
}

// 安全示例:改用循环
function safeFactorial(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

堆栈的典型应用场景

堆栈常用于实现函数调用、表达式求值、括号匹配等场景。例如实现括号匹配检查器:

function isBalanced(expr) {
  const stack = [];
  const map = {
    '(': ')',
    '[': ']',
    '{': '}'
  };

  for (let char of expr) {
    if (char in map) {
      stack.push(char);
    } else if (Object.values(map).includes(char)) {
      if (stack.length === 0 || map[stack.pop()] !== char) {
        return false;
      }
    }
  }

  return stack.length === 0;
}

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

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

相关文章

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-contain…

js实现图片预览

js实现图片预览

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

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="sli…

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获取 j…