232. Implement Queue using Stacks
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false解题要点:
Last updated
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns falseLast updated
class MyQueue {
Stack<Integer> s1 = null;
Stack<Integer> s2 = null;
int size;
boolean done;
/** Initialize your data structure here. */
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
size = 0;
}
/** Push element x to the back of queue. */
public void push(int x) {
while(s1.size() > 0){
// 转到s2
s2.push(s1.pop());
}
s2.push(x);
while(s2.size() > 0){
s1.push(s2.pop());
}
size++;
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
size--;
return s1.pop();
}
/** Get the front element. */
public int peek() {
return s1.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return size == 0;
}
}
/**
* 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();
*/