36 lines
856 B
JavaScript
36 lines
856 B
JavaScript
import Stack from '../stack/index.js';
|
||
|
||
/**
|
||
*
|
||
* @param {Stack} stack 需要处理的栈
|
||
* 思路:我们首先需要有一个把栈底元素弹出的方法,当获取栈底元素之后,我们只需把剩余的元素逆序,再把这个
|
||
* 栈底元素插入栈顶即可。
|
||
*/
|
||
function reverse(stack) {
|
||
if (stack.isEmpty()) return;
|
||
const last = bottomOut(stack); // 弹出栈的底部元素
|
||
reverse(stack);
|
||
stack.push(last);
|
||
}
|
||
|
||
/**
|
||
*
|
||
* @param {Stack} stack - 需要处理的栈
|
||
* @description 将一个栈的底部元素弹出
|
||
* @return number
|
||
*/
|
||
function bottomOut(stack) {
|
||
const ans = stack.pop();
|
||
if (stack.isEmpty()) {
|
||
return ans;
|
||
}
|
||
const last = bottomOut(stack);
|
||
stack.push(ans);
|
||
return last;
|
||
}
|
||
|
||
const stack = new Stack([1, 2, 3, 4, 5, 6, 7]); // 创建一个栈,栈顶元素为5
|
||
|
||
reverse(stack);
|
||
stack.print();
|