See More

package stack; import java.util.Stack; public class Stack232 { public static void main(String[] args) { MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); System.out.println(queue.peek()); // 返回 1 System.out.println(queue.pop()); // 返回 1 System.out.println(queue.empty()); // 返回 false } static class MyQueue { private Stack stackIn, stackOut; /** Initialize your data structure here. */ public MyQueue() { stackIn = new Stack<>(); stackOut = new Stack<>(); } /** Push element x to the back of queue. */ public void push(int x) { stackIn.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if (stackOut.isEmpty()) { while (!stackIn.isEmpty()) { stackOut.push(stackIn.pop()); } } return stackOut.pop(); } /** Get the front element. */ public int peek() { if (stackOut.isEmpty()) { while (!stackIn.isEmpty()) { stackOut.push(stackIn.pop()); } } return stackOut.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return stackIn.isEmpty() && stackOut.isEmpty(); } } }