Solution URL
https://leetcode.com/submissions/detail/411969247/
代码
class MyQueue {
//https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/yong-zhan-shi-xian-dui-lie-by-leetcode/
//Time: O(N) and Space: O(N) for PUSH operation
//Time: O(1) and Space: O(1) for OTHER operations
Stack s1;
Stack s2;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack();
s2 = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
//将stack1中所有元素弹出,依次存入stack2
while(!s1.isEmpty()){
s2.push(s1.pop());
}
//将x压入stack2
s2.push(x);
//将stack2中所有元素弹出,依次存入stack1
while(!s2.isEmpty()){
s1.push(s2.pop());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return (Integer)s1.pop();
}
/** Get the front element. */
public int peek() {
return (Integer)s1.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.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();
*/