其他分享
首页 > 其他分享> > 225. Implement Stack using Queues

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();
 */

标签:int,Queues,pop,num,dataqueue,push,using,225,helpqueue
来源: https://www.cnblogs.com/Manual-Linux/p/12059177.html