用两个栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty)
import java.util.Stack; class MyQueue { Stack<Integer> inStack; Stack<Integer> outStack; /** Initialize your data structure here. */ public MyQueue() { inStack = new Stack<Integer>(); outStack = new Stack<Integer>(); } /** Push element x to the back of queue. */ public void push(int x) { inStack.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { if(outStack.isEmpty()){ while(!inStack.isEmpty()){ outStack.push(inStack.pop()); } } return outStack.pop(); } /** Get the front element. */ public int peek() { if(outStack.isEmpty()){ while(!inStack.isEmpty()){ outStack.push(inStack.pop()); } } return outStack.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { if(inStack.isEmpty()&&outStack.isEmpty()){ return true; }else{ return false; } } }

浙公网安备 33010602011771号