栈数据结构

date
Mar 12, 2023
slug
js-stack
status
Published
tags
JavaScript数据结构与算法
stack
JavaScript
summary
JavaScript Stack init with array
type
Post

创建一个基于数组的栈

class Stack{
    constructor(){
        this.items = [];
    }
}
  • push(element): 添加一个新元素到栈顶
  • pop(): 移除栈顶的元素,同时返回被移除的元素
  • peek(): 返回栈顶的元素,不对栈做任何修改
  • isEmpty(): 如果栈里面没有任何元素就返回 true,否则返回 false
  • clear(): 移除栈里的所有元素
  • size(): 返回栈里的元素个数

向栈添加元素

只添加元素到栈顶
push(element){
    this.items.push(element);
}

从栈移除元素

移除最后添加的元素
pop(){
    return this.items.pop();
}

查看栈顶元素

peek(){
    return this.items[this.items.length - 1];
}
类的内部使用数组保存元素,访问数组的最后一个元素可以用 length - 1
notion image
​ 上图为包含三个元素的栈,内部数组的长度为3。数组中最后一项的位置为2(length - 1)

检查栈是否为空

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

清空栈元素

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

使用Stack类

首先需要初始化 Stack 类,然 后验证一下栈是否为空(输出是 true,因为还没有往栈里添加元素)。
const stack = new Stack(); 
console.log(stack.isEmpty()); // 输出为 true
接下来,往栈里添加一些元素
stack.push(5); 
stack.push(8);
如果调用 peek 方法,将输出 8,因为它是往栈里添加的最后一个元素。
console.log(stack.peek()); // 输出 8
再添加一个元素。
stack.push(11); 
console.log(stack.size()); // 输出 3 
console.log(stack.isEmpty()); // 输出 false
tack.push(15);
notion image
调用两次 pop 方法从栈里移除两个元素。
stack.pop(); 
stack.pop(); 
console.log(stack.size()); // 输出 2
notion image

© shallrise 2025