/**
* 232. Implement Queue using Stacks
* 1. Time:O() Space:O()
* 2. Time:O() Space:O()
*/
// 1. Time:O() Space:O()
class MyQueue {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
private int front;
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
if(s1.empty())
front = x;
while(!s1.empty())
s2.push(s1.pop());
s2.push(x);
while(!s2.empty())
s1.push(s2.pop());
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int tmp = s1.pop();
if(!s1.empty())
front = s1.peek();
return tmp;
}
/** Get the front element. */
public int peek() {
return front;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty();
}
}
// 2. Time:O() Space:O()
class MyQueue {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
private int front;
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
if(s1.empty())
front = x;
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(s2.empty()){
while(!s1.empty())
s2.push(s1.pop());
}
return s2.pop();
}
/** Get the front element. */
public int peek() {
if(!s2.empty())
return s2.peek();
return front;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.empty() && s2.empty();
}
}