algorighm/recursion/逆序一个栈.js
2025-03-07 20:25:12 +08:00

36 lines
856 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();