ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ import java.util.Stack; /** * 只使用栈和递归逆序一个栈 */ public class Algorithm02 { public static void main(String[] args) { StackUtil stack = new StackUtil(); Stack<Integer> nums = new Stack<>(); nums.push(1); nums.push(2); nums.push(3); nums.push(4); nums.push(5); stack.reverse(nums); Integer result = null; while((result = nums.peek()) != null){ System.out.println(nums.pop()); } } } class StackUtil { private Integer getMin(Stack<Integer> stack) { Integer result = stack.pop(); if (stack.isEmpty()) { return result; } else { Integer minNum = getMin(stack); stack.push(result); return minNum; } } public void reverse(Stack stack) { if (stack != null && !stack.isEmpty()) { Integer result = getMin(stack); reverse(stack); stack.push(result); } } } ~~~