hello-algo/codes/javascript/chapter_stack_and_queue/array_stack.js

76 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-12-09 00:05:17 +08:00
/**
* File: array_stack.js
2022-12-09 00:05:17 +08:00
* Created Time: 2022-12-09
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
/* 基于数组实现的栈 */
class ArrayStack {
#stack;
2022-12-09 00:05:17 +08:00
constructor() {
this.#stack = [];
2022-12-09 00:05:17 +08:00
}
2022-12-09 00:05:17 +08:00
/* 获取栈的长度 */
get size() {
return this.#stack.length;
2022-12-09 00:05:17 +08:00
}
/* 判断栈是否为空 */
isEmpty() {
return this.#stack.length === 0;
2022-12-09 00:05:17 +08:00
}
/* 入栈 */
push(num) {
this.#stack.push(num);
2022-12-09 00:05:17 +08:00
}
/* 出栈 */
pop() {
if (this.isEmpty()) throw new Error('栈为空');
return this.#stack.pop();
2022-12-09 00:05:17 +08:00
}
/* 访问栈顶元素 */
top() {
if (this.isEmpty()) throw new Error('栈为空');
return this.#stack[this.#stack.length - 1];
2022-12-09 00:05:17 +08:00
}
/* 返回 Array */
toArray() {
return this.#stack;
2022-12-09 00:05:17 +08:00
}
}
2022-12-09 00:05:17 +08:00
/* Driver Code */
/* 初始化栈 */
const stack = new ArrayStack();
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
console.log('栈 stack = ');
2022-12-09 00:05:17 +08:00
console.log(stack.toArray());
/* 访问栈顶元素 */
const top = stack.top();
console.log('栈顶元素 top = ' + top);
2022-12-09 00:05:17 +08:00
/* 元素出栈 */
const pop = stack.pop();
console.log('出栈元素 pop = ' + pop + ',出栈后 stack = ');
2022-12-09 00:05:17 +08:00
console.log(stack.toArray());
/* 获取栈的长度 */
const size = stack.size;
console.log('栈的长度 size = ' + size);
2022-12-09 00:05:17 +08:00
/* 判断是否为空 */
const isEmpty = stack.isEmpty();
console.log('栈是否为空 = ' + isEmpty);