企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ 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(); } } ~~~