C++|算法-栈和队列(用栈实现队列)

算法-栈和队列:用栈实现队列 【C++|算法-栈和队列(用栈实现队列)】使用两个栈实现队列的功能:

  • pop():弹出队头元素。
  • peek():获取队头元素。
  • push(x):从队尾添加元素。
  • empty():队列是否为空。
#include #include using namespace std; class MyQueue{ public: stack stIn; stack stOut; //- push(x):从队尾添加元素。 void push(int x){ stIn.push(x); } //- pop():弹出队头元素。 int pop(){ int res; if(true == stOut.empty()){//将stIn的元素全部出栈,进入stOut while (false == stIn.empty()) { stOut.push(stIn.top()); stIn.pop(); } } res = stOut.top(); stOut.pop(); return res; } //- peek():获取队头元素。 int peek(){ int res = this->pop(); //直接使用上述函数获取 stOut.push(res); //因为弹出来了所以再放回去 return res; } //- empty():队列是否为空。 bool empty(){ if(stIn.empty() && stOut.empty()){ return true; } return false; } }; int main(){ MyQueue myQue; myQue.push(1); myQue.push(2); myQue.push(3); myQue.push(4); cout<<"myQue.empty()=="<

    推荐阅读