232_用栈实现队列
232_用栈实现队列
package 队列.queue; import java.util.Stack; /** * https://leetcode-cn.com/problems/implement-queue-using-stacks/ * @author Huangyujun * */ public class _232_用栈实现队列 { class MyQueue{ private Stack<Integer> inStack; private Stack<Integer> outStack; public MyQueue() { inStack = new Stack<>(); outStack = new Stack<>(); } public void push(int x) { inStack.push(x); } public int pop() { checkOutStack(); return outStack.pop(); } public int peek() { checkOutStack(); return outStack.peek(); } private void checkOutStack() { while(outStack.isEmpty()) { while(!inStack.isEmpty()) { outStack.push(inStack.pop()); } } } public boolean empty() { return inStack.isEmpty() && outStack.isEmpty(); } } }
本文来自博客园,作者:一乐乐,转载请注明原文链接:https://www.cnblogs.com/shan333/p/15709156.html