Leetcode: Implement Queue using Stacks

来源:互联网 发布:上海滩的少女旗袍淘宝 编辑:程序博客网 时间:2024/05/01 14:47

Implement 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 onlypush 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 Queue {public:    // Push element x to the back of queue.    void push(int x) {        m_secondStack.push(x);    }    // Removes the element from in front of queue.    void pop(void) {        if (m_firstStack.empty()) {            while (!m_secondStack.empty()) {                m_firstStack.push(m_secondStack.top());                m_secondStack.pop();            }        }                m_firstStack.pop();    }    // Get the front element.    int peek(void) {        if (m_firstStack.empty()) {            while (!m_secondStack.empty()) {                m_firstStack.push(m_secondStack.top());                m_secondStack.pop();            }        }        return m_firstStack.top();    }    // Return whether the queue is empty.    bool empty(void) {        return m_firstStack.empty() && m_secondStack.empty();    }    private:    stack<int> m_firstStack;    stack<int> m_secondStack;};

0 0