Leetcode 225. Implement Stack using Queues
Leetcode problem 225 requires us to implement a Stack using Queues. The goal is to implement the following operations for the stack:
void push(int x)
: Push element x onto stack.int pop()
: Removes the element on top of the stack and returns it.int top()
: Get the top element.bool empty()
: Returns whether the stack is empty.std::queue
) or double-ended queues (std::deque
), or is it restricted to a specific type?
std::queue
) are to be used.push
or pop
or should we try to balance the efficiency of both?
Here’s the implementation of the Stack using Queues:
#include <queue>
class MyStack {
private:
std::queue<int> q1; // Main queue to hold stack elements
public:
MyStack() {
}
// Push element x onto stack.
void push(int x) {
int size = q1.size();
q1.push(x);
// Move all elements before x to the back of the queue to maintain stack order
for(int i = 0; i < size; i++) {
q1.push(q1.front());
q1.pop();
}
}
// Removes the element on top of the stack and returns it.
int pop() {
int topElement = q1.front();
q1.pop();
return topElement;
}
// Get the top element.
int top() {
return q1.front();
}
// Returns whether the stack is empty.
bool empty() {
return q1.empty();
}
};
Using a Single Queue: We use a single queue q1
to simulate stack operations.
x
, we first get the size of the queue.x
.x
to the back of the queue. This ensures that element x
is always at the front, simulating stack behavior.By leveraging a single queue and adjusting its order during insertions, we maintain the stack’s LIFO (Last In, First Out) property efficiently for typical stack operations.
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?