【Leetcode C++】1_4. [code] 用队列实现栈

4. [code] 用队列实现栈

4.1. 题目

Leetcode 223

使用队列实现栈的下列操作:

push(x) – 元素 x 入栈;

pop() – 移除栈顶元素;

top() – 获取栈顶元素;

empty() – 返回栈是否为空;

4.2. 思路

4.3. 代码

# include 
class MyStack {
public:
    /** Initialize your data structure here. */
    MyStack() {
        
    }
    
    /** Push element x onto stack. */
    void push(int x) {
      std::queue temp_queue;
      temp_queue.push(x);
      while(!_data.empty()){
        temp_queue.push(_data.front());//
        _data.pop();
      }
      while(!temp_queue.empty()){
        _data.push(temp_queue.front());
        temp_queue.pop();
      }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
       int x = _data.front();
       _data.pop();
       return x; 
    }
    
    /** Get the top element. */
    int top() {
        return _data.front();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return _data.empty();
    }
private:
    std::queue _data;
};

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack* obj = new MyStack();
 * obj->push(x);
 * int param_2 = obj->pop();
 **/

你可能感兴趣的:(C++,Leetcode,C++,刷题之路)