使用栈实现队列 (leetcode 232)

一:解题思路

解题方法:用2个栈实现队列

二:完整代码示例 (C++、Java、Python)

C++:

class MyQueue {
public:
    /** Initialize your data structure here. */
    stack<int> m_in;
    stack<int> m_out;

    MyQueue() 
    {
    }

    void transferIfEmpty()
    {
        if (m_out.empty())
        {
            while (!m_in.empty())
            {
                m_out.push(m_in.top());
                m_in.pop();
            }
        }
    }

    /** Push element x to the back of queue. */
    void push(int x) 
    {
        m_in.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() 
    {
        transferIfEmpty();
        int ret = m_out.top();
        m_out.pop();

        return ret;
    }

    /** Get the front element. */
    int peek() 
    {
        transferIfEmpty();

        return m_out.top();
    }

    /** Returns whether the queue is empty. */
    bool empty() 
    {
        return m_in.empty() && m_out.empty();
    }
};

Java:

class MyQueue
{
    private Stack<Integer> m_in=new Stack<>();
    private Stack<Integer> m_out=new Stack<>();
    
    void transferIfEmpty()
    {
        if(m_out.empty())
        {
            while (!m_in.empty())
            {
                m_out.push(m_in.pop());
            }
        }
    }

    /** Initialize your data structure here. */
    public MyQueue()
    {

    }

    /** Push element x to the back of queue. */
    public void push(int x) 
    {
           m_in.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() 
    {
          transferIfEmpty();
          
          return m_out.pop();
    }

    /** Get the front element. */
    public int peek() 
    {
        transferIfEmpty();
        
        return m_out.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() 
    {
          return m_in.empty()&&m_out.empty();
    }
}

Python:

class MyQueue:

    def __init__(self):
       
        self.stack_in=[]
        self.stack_out=[]


    def push(self, x: int) -> None:
        
        self.stack_in.append(x)
        

    def pop(self) -> int:
        self.peek()
        
        return self.stack_out.pop()
        


    def peek(self) -> int:
        if self.stack_out: return self.stack_out[-1]
        self.stack_out=self.stack_in[::-1]
        self.stack_in=[]
        
        return self.stack_out[-1]


    def empty(self) -> bool:
        
        return not self.stack_in and not self.stack_out

 

posted @ 2020-03-18 18:07  repinkply  阅读(171)  评论(0)    收藏  举报