栈(stack)是一种遵循先入后出逻辑的线性数据结构。
堆叠元素的顶部称为“栈顶”,底部称为“栈底”。将把元素添加到栈顶的操作叫作“入栈”,删除栈顶元素的操作叫作“出栈”。
栈的特点:先进后出, 后进先出。

栈的常用操作
栈的实现
栈可以视为一种受限制的数组或链表。
基于链表的实现
使用链表实现栈时,我们可以将链表的头节点视为栈顶,尾节点视为栈底。
对于入栈操作,我们只需将元素插入链表头部,这种节点插入方法被称为“头插法”。而对于出栈操作,只需将头节点从链表中删除即可。
/* 基于链表实现的栈 */
class LinkedListStack {
#stackPeek; // 将头节点作为栈顶
#stkSize = 0; // 栈的长度
constructor() {
this.#stackPeek = null;
}
/* 获取栈的长度 */
get size() {
return this.#stkSize;
}
/* 判断栈是否为空 */
isEmpty() {
return this.size === 0;
}
/* 入栈 */
push(num) {
const node = new ListNode(num);
node.next = this.#stackPeek;
this.#stackPeek = node;
this.#stkSize++;
}
/* 出栈 */
pop() {
const num = this.peek();
this.#stackPeek = this.#stackPeek.next;
this.#stkSize--;
return num;
}
/* 访问栈顶元素 */
peek() {
if (!this.#stackPeek) throw new Error('栈为空');
return this.#stackPeek.val;
}
/* 将链表转化为 Array 并返回 */
toArray() {
let node = this.#stackPeek;
const res = new Array(this.size);
for (let i = res.length - 1; i >= 0; i--) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
基于数组的实现
使用数组实现栈时,我们可以将数组的尾部作为栈顶。入栈与出栈操作分别对应在数组尾部添加元素与删除元素
/* 基于数组实现的栈 */
class ArrayStack {
#stack;
constructor() {
this.#stack = [];
}
/* 获取栈的长度 */
get size() {
return this.#stack.length;
}
/* 判断栈是否为空 */
isEmpty() {
return this.#stack.length === 0;
}
/* 入栈 */
push(num) {
this.#stack.push(num);
}
/* 出栈 */
pop() {
if (this.isEmpty()) throw new Error('栈为空');
return this.#stack.pop();
}
/* 访问栈顶元素 */
top() {
if (this.isEmpty()) throw new Error('栈为空');
return this.#stack[this.#stack.length - 1];
}
/* 返回 Array */
toArray() {
return this.#stack;
}
}
两种实现对比
时间效率
- 基于数组实现的栈在触发扩容时效率会降低,但由于扩容是低频操作,因此平均效率更高。
- 基于链表实现的栈可以提供更加稳定的效率表现。
空间效率
基于数组实现的栈可能造成一定的空间浪费。
链表节点需要额外存储指针,因此链表节点占用的空间相对较大。
栈的典型应用
- 浏览器中的后退与前进、软件中的撤销与反撤销。每当我们打开新的网页,浏览器就会对上一个网页执行入栈,这样我们就可以通过后退操作回到上一个网页。后退操作实际上是在执行出栈。如果要同时支持后退和前进,那么需要两个栈来配合实现。
- 程序内存管理。每次调用函数时,系统都会在栈顶添加一个栈帧,用于记录函数的上下文信息。在递归函数中,向下递推阶段会不断执行入栈操作,而向上回溯阶段则会不断执行出栈操作。
- 撤销(undo)和反撤销(redo)具体是如何实现的?
使用两个栈,栈 A 用于撤销,栈 B 用于反撤销。
- 每当用户执行一个操作,将这个操作压入栈
A,并清空栈B。 - 当用户执行“撤销”时,从栈
A中弹出最近的操作,并将其压入栈B。 - 当用户执行“反撤销”时,从栈
B中弹出最近的操作,并将其压入栈A
- 利用栈结构的特点封装实现十进制转换为二进制的方法。
function dec2bin(dec) {
// new 一个 Stack,保存余数
const stack = new Stack();
// 当不确定循环次数时,使用 while 循环
while (dec > 0) {
// 除二取余法
stack.push(dec % 2); // 获取余数,放入栈中
dec = Math.floor(dec / 2); // 除数除以二,向下取整
}
let binaryString = "";
// 不断地从栈中取出元素(0 或 1),并拼接到一起。
while (!stack.isEmpty()) {
binaryString += stack.pop();
}
return binaryString;
}