Implement Queue using Stacks

class Queue {
public:
   stack<int>sta1;
   stack<int>sta2;
    // Push element x to the back of queue.
    /*
    入栈:把元素push到sta1中;
    出栈:sta2作为辅助栈,如果sta2不为空,则把sta2中的元素挨个出站,然后把sta1的元素压入sta2中,把栈顶元素出栈.最后要把sta2中的元素压入sta1中
    */
    void push(int x) {
        sta1.push(x);
       
       
    }

    // Removes the element from in front of queue.
    void pop(void) {
       
        while( !sta1.empty())
        { sta2.push(sta1.top());
         sta1.pop();
        }
        sta2.pop();
        while( !sta2.empty())//pop()之后要把sta2中的元素压入sta1中
        {
        sta1.push(sta2.top());
        sta2.pop();
        }
    }

    // Get the front element.
    int peek(void) {
        int a = 0;

        while(!sta1.empty())
        {sta2.push(sta1.top());
         sta1.pop();
        }
        a=sta2.top();
        while( !sta2.empty())//pop()之后要把sta2中的元素压入sta1中
        {
        sta1.push(sta2.top());
        sta2.pop();
        }
        return a;
    }

    // Return whether the queue is empty.
    bool empty(void) {
       
      return ( sta1.empty() && sta2.empty());
       
    }
};

原文地址:https://www.cnblogs.com/gofighting/p/5036199.html