feat: 逆序一个栈

This commit is contained in:
LouisFonda 2025-03-07 20:25:12 +08:00
parent 27d3b489e3
commit 9a4d2d388f
Signed by: yigencong
GPG Key ID: 29CE877CED00E966
3 changed files with 39 additions and 1 deletions

View File

@ -1 +1 @@
export * from './link-list.js' export * from './link-list.js';

3
recursion/recursion.md Normal file
View File

@ -0,0 +1,3 @@
# 递归
此目录存放了常用递归思路,以及一些解决方案

View File

@ -0,0 +1,35 @@
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();