class MyQueue {
//先建立两个栈,stackIn用于模拟入队
Stack<Integer> stackIn;
//stackIn用于模拟出队
Stack<Integer> stackOut;
public MyQueue() {
//初始化这两个栈
stackIn = new Stack<Integer>();
stackOut = new Stack<Integer>();
}
//入队列和入栈的操作一样
public void push(int x) {
stackIn.push(x);
}
//出队列就不一样了
public int pop() {
//先判断stackOut是否是空
if(stackOut.isEmpty()){
//如果为空,把stackIn中的元素弹出来放到stackOut中
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
//再把stackOut中的元素弹出来,此时出栈的顺序就和队列出队的顺序一致
return stackOut.pop();
}
//peek()和pop()是一个道理,只有最后一个返回语句不一样
public int peek() {
if(stackOut.isEmpty()){
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
return stackOut.peek();
}
//判断队列是否为空,就要判断两个栈是否都为空
public boolean empty() {
return stackIn.isEmpty()&&stackOut.isEmpty();
}
}
/**
* 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();
*/
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交