232.用栈实现队列 https://leetcode-cn.com/problems/implement-queue-using-stacks/
要点:
出栈: 只需关注outStack
,如果里面有值,直接出栈,
如果没有,从inStack
将值pop到outStack
,再从outStack
中pop出来,
入栈: 直接入inStack
class MyQueue {
private Stack<Integer> inStack;
private Stack<Integer> outStack;
/** Initialize your data structure here. */
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
/** 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() {
shift();
if (!outStack.isEmpty()) {
return outStack.pop();
}
throw new RuntimeException("队列里没有元素");
}
public void shift(){
if(outStack.isEmpty()){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
/** Get the front element. */
public int peek() {
shift();
if (!outStack.isEmpty()) {
return outStack.peek();
}
throw new RuntimeException("队列里没有元素");
}
/** Returns whether the queue is empty. */
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}
网友评论