题目描述
描述:用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
数据范围: n≤1000。
要求:存储n个元素的空间复杂度为 O(n) ,插入与删除的时间复杂度都是 O(1)。
输入:["PSH1","PSH2","POP","POP"]
返回值:1,2
说明:
"PSH1":代表将1插入队列尾部
"PSH2":代表将2插入队列尾部
"POP“:代表删除一个元素,先进先出=>返回1
"POP“:代表删除一个元素,先进先出=>返回2
输入:["PSH2","POP","PSH1","POP"]
返回值:2,1
解题思路
用两个栈实现队列:最直观的是,一个栈stack1作为入栈,一个栈stack2作为出栈,栈是先进后出,队列是先进先出,所以一个栈无法实现队列,我们需要两个栈来实现,先进后出再先进后出就是先进先出啦。在队列尾部插入整数(push)即直接向stack1中插入元素即可;在队列头部删除整数(pop)即首先判断stack2是否为空,如果不为空则直接从stack2中弹出元素,反之则将stack1中的元素全部弹出来压入stack2中,待到stack1为空时,从stack2中弹出最后一个元素即可,记得要先判断stack2是否为空,这样才不会打乱顺序。
class Solution
{
public:
void push(int node) {
stack1.push(node); //入栈就是直接入栈
}
int pop() {
int node;
if(!stack2.empty())
{
node=stack2.top();
stack2.pop();
}
else
{
while(!stack1.empty())
{
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
node=stack2.top();
stack2.pop();
}
return node;
}
private:
stack<int> stack1; //入栈
stack<int> stack2; //出栈
};
上述代码的pop部分有些冗余,尝试优化一下,注意在刷题中,先尝试逻辑清晰,再尝试优化代码,这样才会理解更加深入~
class Solution
{
public:
void push(int node) {
stack1.push(node); //入栈就是直接入栈
}
int pop() {
int node;
if(stack2.empty())
{
while(!stack1.empty())
{
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
}
node=stack2.top();
stack2.pop();
return node;
}
private:
stack<int> stack1; //入栈
stack<int> stack2; //出栈
};