232. 用栈实现队列
作者:互联网
题目
https://leetcode-cn.com/problems/implement-queue-using-stacks/
思路
创建两个栈,一个专门用来pop()数据,一个专门用来存数据。
当stackPop不为空的时候(stackPop的数够用,pop(),peek()可以正常操作),stackPush()就用来存后边add来的数。
当stackPop为空的时候,就把stackPush()的数全都倒进stackPop()
注意,peek(),pop(),操作的时候,很可能stackPop的数据已经用完了,所以要把存着的数倒进去
push()无所谓,但是也可以加上pushToPop()
代码
class MyQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
/** Initialize your data structure here. */
public MyQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
//当pop没有数,但是push里面有数的时候,更新pop
private void pushToPop(){
if (stackPop.isEmpty()){
while (!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
}
/** Push element x to the back of queue. */
public void push(int x) {
stackPush.push(x);
pushToPop();
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stackPop.isEmpty() && stackPush.isEmpty()){
throw new RuntimeException("Queue is empty");
}
pushToPop();
return stackPop.pop();
}
/** Get the front element. */
public int peek() {
if (stackPop.isEmpty() && stackPush.isEmpty()){
throw new RuntimeException("Queue is empty");
}
pushToPop();
return stackPop.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if (stackPop.isEmpty() && stackPush.isEmpty()){
return true;
}
return false;
}
}
标签:队列,stackPop,pop,stackPush,pushToPop,用栈,isEmpty,public,232 来源: https://blog.csdn.net/weixin_51125132/article/details/118398331