Leetcode / 232. Implement Queue using Stacks
Pick a programming language:
Here is the source code for the solution to this problem.
import java.util.Stack;
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
if (stack2.empty()) {
while (!stack1.empty()) {
Integer popped = stack1.pop();
stack2.push(popped);
}
}
// assumption: stack2 is not empty, call to pop() valid and not trying to
// bring up exception for not having anything in queue
return stack2.pop();
}
public int peek() {
if (stack2.empty()) {
while (!stack1.empty()) {
Integer popped = stack1.pop();
stack2.push(popped);
}
}
return stack2.peek();
}
public boolean empty() {
return stack1.empty() && 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();
* boolean param_4 = obj.empty();
*/
Did you like the lesson? 😆👍
Consider a donation to support our work: