力扣刷题记录29.1-----225. 用队列实现栈

目录

  • 一、题目
  • 二、代码
  • 三、运行结果


一、题目

力扣刷题记录29.1-----225. 用队列实现栈_第1张图片

二、代码

class MyStack {
public:
     
    queue<int> queue_real;  //真实用于模拟栈的队列
    queue<int> queue_help;   //辅助队列
    int first_num=0;
    MyStack() {

    }
    
    void push(int x) {

        queue_help.push(x);  //流水
        while(!queue_real.empty()) 
        {
        queue_help.push(queue_real.front());
        queue_real.pop();
        }
        while(!queue_help.empty())
        {
        queue_real.push(queue_help.front());
        queue_help.pop();            
        }
    }
    
    int pop() {
    
    first_num=queue_real.front();
    queue_real.pop();
    return first_num;

    }
    
    int top() {

    return queue_real.front();
    }
    
    bool empty() {
     
    return queue_real.empty();

    }
};

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

三、运行结果

力扣刷题记录29.1-----225. 用队列实现栈_第2张图片

你可能感兴趣的:(#,leetcode,算法,c++)