栈简介
- 一个后进先出的数据结构
- javascript没有栈,可以用array数据结构模拟栈的功能
栈实现
- size: 栈的大小
- max: 栈的最大容量
- sp: 栈指针
- Stack Overflow: 栈溢出(异常)
- Stack Underflow: 栈下溢(异常)


入栈示例

出栈示例(Stack Underflow)

入栈示例 (Stack Overflow)



出栈示例

class Stack {
constructor(max = 1000) {
this.max = max;
this.sp = -1;
this.data = Array.from({ length: max });
}
push(item) {
if (this.sp === this.max - 1) {
throw "Stack Overflow";
}
this.data[++this.sp] = item;
}
pop() {
if (this.sp === -1) {
throw "Stack Underflow";
}
return this.data[this.sp--];
}
}
const stack = new Stack();
stack.push("a");
stack.push("b");
stack.push("c");
console.log(stack.pop());
console.log(stack.pop());
其他问题