225. Implement Stack using Queues

class MyStack 
{
public:
    /** Initialize your data structure here. */
    MyStack() 
    {
        
    }
    
    /** Push element x onto stack. */
    void push(int x)
    {
        dataqueue.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() 
    {
        /*dataqueue中有数据 helpqueue中没有数据*/
        
        int num = 0;
        while(dataqueue.size() > 1)
        {
            helpqueue.push(dataqueue.front());
            dataqueue.pop();
        }
        num = dataqueue.front();
        dataqueue.pop();    
        /*再把数据拷贝回dataqueue*/
        while(helpqueue.size() >= 1)
        {
            dataqueue.push(helpqueue.front());
            helpqueue.pop();
        }
        return num;     
    }
    
    /** Get the top element. */
    int top() 
    {
        /*只是获取顶端元素 但不删除顶端元素*/
        int num = pop();
        push(num);
        return num;
    }
    
    /** Returns whether the stack is empty. */
    bool empty() 
    {
        if(dataqueue.empty() == true && helpqueue.empty() == true)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
private:
    queue<int> dataqueue;
    queue<int> helpqueue;
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->top();
 * bool param_4 = obj->empty();
 */
上一篇:adb命令


下一篇:UOJ #225.排队