clueless coding // TODO: be smarter

LeetCode Implement Queue using Stacks: CPP Solution



TL;DR Code Solution



stack<int> reserve;
stack<int> queue;

/** Initialize your data structure here. */
MyQueue() {

}

/** Push element x to the back of queue. */
void push(int x) {
    reserve.push(x);
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
    if (queue.empty()) {
        while (!reserve.empty()) {
            queue.push(reserve.top());
            reserve.pop();
        }
    }
    int result = queue.top();
    queue.pop();
    return result;
}

/** Get the front element. */
int peek() {
    if (queue.empty()) {
        while (!reserve.empty()) {
            queue.push(reserve.top());
            reserve.pop();
        }
    }
    int result = queue.top();
    return result;
}

/** Returns whether the queue is empty. */
bool empty() {
    return reserve.empty() && queue.empty();
}