今日碎碎念: 我好困啊~~下周答辩希望一切顺利啊
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
知识点
栈stack
#include <stack>
一种先进后出(FILO)的数据结构。
链接: link
队列
一种先进先出(FIFO)的数据结构。
题目分析
这个栈stack就像是一个水杯,队列的pop就是取杯子底下的水,队列push就是取杯口附近的水,两个杯子要想实现杯底和杯面的水任意取,就像是把热水凉凉一样,来回倒来倒去。
代码实现
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while(!stack1.empty()){
temp=stack1.top();
stack2.push(temp);
stack1.pop();
}
queue_pop=stack2.top();
stack2.pop();
while(!stack2.empty()){
temp=stack2.top();
stack1.push(temp);
stack2.pop();
}
return queue_pop;
}
private:
int temp=0; //杯口的水
int queue_pop=0;//杯底的水
stack<int> stack1;
stack<int> stack2;
};
结果
今天这一题真实so easy~