232. Implement Queue using Stacks

mplement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

 思路: 使用两个栈实现访问队列首元素以及弹出队列的第一个元素。

class MyQueue {
public:
    /** Initialize your data structure here. */
    //With two stacks
    stack<int> m_input,m_output;
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        m_input.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int temp=peek();
        m_output.pop();
        return temp;
    }
    
    /** Get the front element. */
    int peek() {
         if(m_output.empty())
         {
             while(!m_input.empty())
                 m_output.push(m_input.top()), m_input.pop(); 
         }
        return m_output.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return m_input.empty()&&m_output.empty();
    }
};
原文地址:https://www.cnblogs.com/zhaoyaxing/p/8503017.html