代码随想录刷题——栈与队列篇(一)
232.用栈实现队列
模拟,和以前刚开始学栈的时候解题的思路有点类似,拿两个栈来“倒腾”出想要的效果:
class MyQueue{ public:stack<int> stIn;stack<int> stOut;MyQueue(){}void push(int x){stIn.push(x);}int pop(){if(!stOut.empty()){int t = stOut.top();stOut.pop();return t;}else{while(!stIn.empty()){stOut.push(stIn.top());stIn.pop();}int t = stOut.top();stOut.pop();return t;}}int peek(){if(!stOut.empty()){return stOut.top();}else{while(!stIn.empty()){stOut.push(stIn.top());stIn.pop();}return stOut.top();}}bool empty(){if(stIn.empty()&&stOut.empty()) return true;return false;} };
其他:
(1)stack的默认pop()函数返回void
(2)stack的top()函数很方便
(3)本题的情况如下图: