import java.util.Stack; class Solution { private static void reverse(Stack<Integer> s) { int x = pop(s); if (s.isEmpty()) { s.push(x); return; } reverse(s); s.push(x); } private static int pop(Stack<Integer> s) { int a = s.pop(); if (s.isEmpty()) { return a; } int b = pop(s); s.push(a); return b; } public static void main(String[] args) { Stack<Integer> a = new Stack<>(); a.push(1); a.push(2); a.push(3); reverse(a); a.forEach(System.out::println); } } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
用递归逆序栈
猜你喜欢
转载自blog.51cto.com/tianyiya/2311933
今日推荐
周排行