b_nk_用递归函数和栈逆序一个栈 & 用一个栈实现另一个栈的排序(栈+递归 | 栈)
用递归函数和栈逆序一个栈
实现栈中元素的逆序,但是只能用递归函数来实现,不能用其他数据结构。
思路:这里因为栈的输出本质也是将栈元素逆序,所以我得先将 st1 逆序为 st2,然后将 st2 用递归逆序...
import java.util.*;
import java.io.*;
class Solution {
int n;
int getBottom(Stack<Integer> st) {
int top = st.pop();
if (st.isEmpty())
return top;
int bottom = getBottom(st);
st.push(top);
return bottom;
}
void reverse(Stack<Integer> st) {
if (st.isEmpty()) return;
int e = getBottom(st);
reverse(st);
st.push(e);
}
void init() throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
Stack<Integer> st1 = new Stack<Integer>(), st2 = new Stack<Integer>();
n = sc.nextInt();
for (int i=0; i<n; i++) st1.push(sc.nextInt());
while (!st1.isEmpty()) st2.push(st1.pop());
reverse(st2);
while (!st2.isEmpty()) {
System.out.print(st2.pop()+" ");
}
}
}
public class Main{
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
用一个栈实现另一个栈的排序
输入
5
5 8 4 3 6
输出
8 6 5 4 3
import java.util.*;
import java.math.*;
import java.io.*;
class Solution {
void init() throws IOException {
Scanner sc = new Scanner(new BufferedInputStream(System.in));
Stack<Integer> data = new Stack<>(), st = new Stack<>();
int n = sc.nextInt();
for (int i=0; i<n; i++) data.push(sc.nextInt());
while (!data.isEmpty()) {
int x = data.pop();
if (st.isEmpty()) {
st.push(x);
} else {
while (!st.isEmpty() && st.peek() > x)
data.push(st.pop());
st.push(x);
}
}
while (!st.isEmpty()) System.out.print(st.pop()+" ");
}
}
public class Main{
public static void main(String[] args) throws IOException {
Solution s = new Solution();
s.init();
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 超详细,DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方Dee
· 用 DeepSeek 给对象做个网站,她一定感动坏了
· .NET 8.0 + Linux 香橙派,实现高效的 IoT 数据采集与控制解决方案
· DeepSeek处理自有业务的案例:让AI给你写一份小众编辑器(EverEdit)的语法着色文件