Leetcode 225. Implement Stack using Queues
Design and implement a stack using queues. Implement the MyStack
class:
void push(int x)
Pushes element x to the top of the stack.int pop()
Removes the element on the top of the stack and returns that element.int top()
Returns the element on the top of the stack.boolean empty()
Returns true
if the stack is empty, false
otherwise.Notes:
enqueue
to add an item to the back of the queue, dequeue
to remove the front item of the queue, peek
, and empty
checks are allowed.Here’s the Java implementation of a stack using a single queue:
import java.util.LinkedList;
import java.util.Queue;
class MyStack {
private Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
int size = queue.size();
queue.add(x);
for (int i = 0; i < size; i++) {
queue.add(queue.remove());
}
}
public int pop() {
return queue.remove();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
System.out.println(stack.top()); // returns 2
System.out.println(stack.pop()); // returns 2
System.out.println(stack.empty()); // returns false
}
}
This approach ensures that the most recently added element is always at the front of the queue, mimicking the LIFO (last-in, first-out) order of a stack.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?