用遞迴逆序棧
阿新 • • 發佈:2018-11-01
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(); */