2022-12-04 10:14:51 +08:00
|
|
|
/**
|
|
|
|
* File: stack.js
|
|
|
|
* Created Time: 2022-12-04
|
|
|
|
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
|
|
|
*/
|
|
|
|
|
2022-12-20 21:33:14 +08:00
|
|
|
/* Driver Code */
|
2022-12-04 10:14:51 +08:00
|
|
|
/* 初始化栈 */
|
|
|
|
// Javascript 没有内置的栈类,可以把 Array 当作栈来使用
|
|
|
|
const stack = [];
|
|
|
|
|
|
|
|
/* 元素入栈 */
|
|
|
|
stack.push(1);
|
|
|
|
stack.push(3);
|
|
|
|
stack.push(2);
|
|
|
|
stack.push(5);
|
|
|
|
stack.push(4);
|
2023-03-03 01:34:53 +08:00
|
|
|
console.log("栈 stack =", stack);
|
2022-12-04 10:14:51 +08:00
|
|
|
|
|
|
|
/* 访问栈顶元素 */
|
2022-12-04 10:22:18 +08:00
|
|
|
const peek = stack[stack.length - 1];
|
2023-03-03 01:34:53 +08:00
|
|
|
console.log("栈顶元素 peek =", peek);
|
2022-12-04 10:14:51 +08:00
|
|
|
|
|
|
|
/* 元素出栈 */
|
2022-12-04 10:22:18 +08:00
|
|
|
const pop = stack.pop();
|
2023-03-03 01:34:53 +08:00
|
|
|
console.log("出栈元素 pop =", pop);
|
|
|
|
console.log("出栈后 stack =", stack);
|
2022-12-04 10:14:51 +08:00
|
|
|
|
|
|
|
/* 获取栈的长度 */
|
2022-12-04 10:22:18 +08:00
|
|
|
const size = stack.length;
|
2023-03-03 01:34:53 +08:00
|
|
|
console.log("栈的长度 size =", size);
|
2022-12-04 10:14:51 +08:00
|
|
|
|
|
|
|
/* 判断是否为空 */
|
2023-03-03 01:34:53 +08:00
|
|
|
const isEmpty = stack.length === 0;
|
|
|
|
console.log("栈是否为空 =", isEmpty);
|