C++ 0ms, one queue simple sol


  • 0
    C

    Queue is FIFO, but Stack is LIFO.
    The key part below is "push". When push a elem to the end of the queue, I mimic it looks like pushing to the head. Then other action is the same as queue's.

    class Stack {
    private:
        queue<int> que;
        int size;
        
    public:
        Stack(){
            size = 0;
        }
        
        // Push element x onto stack.
        void push(int x) {
            que.push(x);
            size++;
            
            int head = que.front();
            while (head != x) {
                que.pop();
                que.push(head);
                head = que.front();
            }
            
        }
        
        // Removes the element on top of the stack.
        void pop(void) {
            if (size == 0) {
                cout << "It's empty!\n";
                return;
            }
            
            que.pop();
            size--;
        }
        
        // Get the top element.
        int top(void) {
            if (size == 0) {
                cout << "No elem on top!\n";
                return INT_MIN;
            }
            return que.front();
        }
        
        // Return whether the stack is empty.
        bool empty(void) {
            return size == 0;
        }
    };

Log in to reply
 

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