zoukankan      html  css  js  c++  java
  • 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();
        }
    };
  • 相关阅读:
    20182316胡泊 实验5报告
    20182316胡泊 第6周学习总结
    20182316胡泊 第5周学习总结
    20182316胡泊 实验4报告
    20182316胡泊 实验3报告
    20182316胡泊 第4周学习总结
    20182316胡泊 第2,3周学习总结
    实验2报告 胡泊
    《数据结构与面向对象程序设计》第1周学习总结
    实验1报告
  • 原文地址:https://www.cnblogs.com/zhaoyaxing/p/8503017.html
Copyright © 2011-2022 走看看