题目需求是使用栈(后进先出)来达到队列的效果(先进先出)。
对此我们可以使用两个栈来完成队列的操作,步骤如下:
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<Integer>();
outStack = new Stack<Integer>();
}
public void push(int x) {
inStack.push(x); //输入栈进栈x
}
public int pop() {
if(outStack.isEmpty()){
inToOut(); //将输入栈的元素,全部入栈输出栈
}
return outStack.pop(); //返回输出栈的栈顶元素
}
public int peek() {
if(outStack.isEmpty()){
inToOut();
}
return outStack.peek();
}
public boolean empty() {
if(inStack.isEmpty()&&outStack.isEmpty()){ //输入栈和输出栈都为空时,模拟队列为空
return true;
}
return false;
}
public void inToOut(){
while(!inStack.isEmpty()){
outStack.push(inStack.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();
*/class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<Integer>();
outStack = new Stack<Integer>();
}
public void push(int x) {
inStack.push(x); //输入栈进栈x
}
public int pop() {
if(outStack.isEmpty()){
inToOut(); //将输入栈的元素,全部入栈输出栈
}
return outStack.pop(); //返回输出栈的栈顶元素
}
public int peek() {
if(outStack.isEmpty()){
inToOut();
}
return outStack.peek();
}
public boolean empty() {
if(inStack.isEmpty()&&outStack.isEmpty()){ //输入栈和输出栈都为空时,模拟队列为空
return true;
}
return false;
}
public void inToOut(){
while(!inStack.isEmpty()){
outStack.push(inStack.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();
*/
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_43598687/article/details/123238489
内容来源于网络,如有侵权,请联系作者删除!