232. Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
public class MyQueue {
public Stack<Integer> stack1 = new Stack<Integer>();
public Stack<Integer> stack2 = new Stack<Integer>();
public void push(int x){
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
stack1.push(x);
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
public int pop(){
return stack2.pop();
}
public int peek(){
return stack2.peek();
}
public boolean empty(){
return stack2.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();
*/
C++:
class MyQueue {
public:
std::stack<int> stack1;
std::stack<int> stack2;
/** Push element x to the back of queue. */
void push(int x) {
while(!stack2.empty()){
stack1.push(stack2.top());
stack2.pop();
}
stack1.push(x);
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res = stack2.top();
stack2.pop();
return res;
}
/** Get the front element. */
int peek() {
return stack2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return stack2.empty();
}
};
/**
* 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();
* bool param_4 = obj.empty();
*/