Leetcode 225 Solution
This article provides solution to leetcode question 225 (implement-stack-using-queues)
Access this page by simply typing in "lcs 225" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/implement-stack-using-queues
Solution
class Stack {
queue<int> q;
public:
// Push element x onto stack.
void push(int x) {
q.push(x);
}
// Removes the element on top of the stack.
void pop() {
for (int i = 0; i < q.size() - 1; i++)
q.push(q.front()), q.pop();
q.pop();
}
// Get the top element.
int top() {
int val = 0;
for (int i = 0; i < q.size(); i++)
q.push(val = q.front()), q.pop();
return val;
}
// Return whether the stack is empty.
bool empty() {
return q.size() == 0;
}
};