Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x) { a.emplace(x); }
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (std::empty(b)) {
while (!std::empty(a)) {
int t = a.top();
a.pop();
b.emplace(t);
}
}
int res = b.top();
b.pop();
return res;
}
/** Get the front element. */
int peek() {
if (std::empty(b)) {
while (!std::empty(a)) {
int t = a.top();
a.pop();
b.emplace(t);
}
}
return b.top();
}
/** Returns whether the queue is empty. */
bool empty() { return std::empty(a) && std::empty(b); }
private:
stack<int> a;
stack<int> b;
};