一、题目
二、代码
class MyQueue {
Stack<Integer> stack_in;
Stack<Integer> stack_out;
//核心是: in 和 out 完成反转
public MyQueue() {
stack_in = new Stack<>();
stack_out = new Stack<>();
}
public void push(int x) {
stack_in.push(x);
}
public int pop()
{
//out为空 in 不为空 导入
empty_stack_in();
return stack_out.pop();
}
public int peek()
{
//out为空 in 不为空 导入
empty_stack_in();
return stack_out.peek();
}
public boolean empty()
{
return stack_in.isEmpty() && stack_out.isEmpty();
}
public void empty_stack_in()
{
if(stack_out.isEmpty()==false) return ;
while(!stack_in.isEmpty())
{
stack_out.push(stack_in.peek());
stack_in.pop();
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/