Cracking the Coding Interview: Queues: A Tale of Two Stacks

Here’s my solution to the challenge: https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks

class MyQueue {

    public:
        stack stack_newest_on_top, stack_oldest_on_top;
    void push(int x) {
        stack_newest_on_top.push(x);
    }

    void pop() {
        if (stack_oldest_on_top.empty()) {
            while (!stack_newest_on_top.empty()) {
                stack_oldest_on_top.push(stack_newest_on_top.top());
                stack_newest_on_top.pop();
            }
        }
        return stack_oldest_on_top.pop();
    }

    int front() {
        if (stack_oldest_on_top.empty()) {
            while (!stack_newest_on_top.empty()) {
                stack_oldest_on_top.push(stack_newest_on_top.top());
                stack_newest_on_top.pop();
            }
        }
        return stack_oldest_on_top.top();
    }
};

All my solutions to HackerRank challenges can be found here: https://github.com/sdulaney/hackerrank

Leave a Comment