Implement stack using queues
XXX. Implement Stack Using Queues
Queue
Design
Problem Statement:
Implement a last-in-first-out (LIFO) stack using only queues. The implemented stack should support the following operations:
push(int x)
: Push elementx
onto the stack.pop()
: Removes the element on top of the stack and returns it.top()
: Get the top element.empty()
: Return whether the stack is empty.
You must use only standard queue operations — add
, poll
, peek
, and isEmpty
. Implement the stack such that the top
and pop
operations have O(1) time complexity.
Algorithm:
To simulate a stack using a single queue:
-
For the
push
operation:- Add the new element to the queue.
- Rotate the queue by moving the front elements to the back, keeping the new element at the front.
-
For the
pop
operation:- Remove the front element of the queue.
-
For the
top
operation:- Return the front element of the queue without removing it.
-
For the
empty
operation:- Check if the queue is empty.
Complexity:
Time Complexity:
push
: O(n), wheren
is the number of elements in the queue (due to rotation).pop
: O(1), as removing the front element of the queue is constant time.top
: O(1), as peeking the front element is constant time.empty
: O(1), as checking if the queue is empty is constant time.
n
is the number of elements in the stack (stored in the queue).
Java Implementation:
class MyStack {
private Queue queue = new LinkedList<>();
/** Push element x onto stack. */
public void push(int x) {
queue.add(x);
for (int i = 1; i < queue.size(); i++)
queue.add(queue.remove());
}
/** Removes the element on top of the stack and returns it. */
public int pop() {
return queue.remove();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}