NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
~~~ import java.util.Stack; /** * 用两个栈实现队列 */ public class Algorithm01 { public static void main(String arg[]) { StackQueue queue = new StackQueue(); queue.add(10); queue.add(12); queue.add(1); queue.add(3); Integer result = null; while ((result = queue.poll()) != null) { System.out.println(result); } } } // 用栈实现队列 class StackQueue { private Stack<Integer> pushStack = new Stack<>(); private Stack<Integer> popStack = new Stack<>(); private void pushToPopStack() { if (popStack.isEmpty()) { while (!pushStack.empty()) { popStack.push(pushStack.pop()); } } } public void add(Integer num) { if (num == null) { throw new RuntimeException("num is null"); } pushStack.push(num); pushToPopStack(); } public Integer poll() { if (pushStack.isEmpty() && popStack.isEmpty()) { throw new RuntimeException("stack is empty"); } pushToPopStack(); return popStack.pop(); } public Integer peek() { if (pushStack.isEmpty() && popStack.isEmpty()) { throw new RuntimeException("stack is empty"); } pushToPopStack(); return popStack.pop(); } } ~~~