O(1) for all operations in C++


  • 0
    M

    Inspired by the O(1) Java and Javascript solutions.

    class Stack {
    public:
        std::queue<void*>* queue = new std::queue<void*>;
        
        // Push element x onto stack.
        void push(int x) {
            int* pushElem = new int(x);
            std::queue<void*>* newQueue = new std::queue<void*>;
            newQueue->push(pushElem);
            newQueue->push(queue);
            queue = newQueue;
        }
        
        // Removes the element on top of the stack.
        void pop() {
            int* popElem = (int*)queue->front();
            queue->pop();
            delete popElem;
            
            std::queue<void*>* newQueue = (std::queue<void*>*)queue->front();
            queue->pop();
            delete queue;
            queue = newQueue;
        }
        
        // Get the top element.
        int top() {
            int* popElem = (int*)queue->front();
            return *popElem;
        }
        
        // Return whether the stack is empty.
        bool empty() {
            return queue->empty();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.