代码随想录Day |
232.用栈实现队列
文档讲解:代码随想录
视频讲解: 栈的基本操作| LeetCode:232.用栈实现队列
状态:√
加强一下栈的理解,主要是寻找第一个元素的区别,先将元素压入到另一个栈里得到入栈时的顺序排列
int pop() {
int res;
//如果出栈不为空,那么返回出栈的顶端数据
if(!stackOut.empty())
{
res = stackOut.top();
}
//如果为空,则把入栈里的元素压入出栈
else
{
while(!stackIn.empty())
{
stackOut.push(stackIn.top());
stackIn.pop();
}
res = stackOut.top();
}
stackOut.pop();
return res;
}
用队列实现栈
文档讲解:代码随想录
视频讲解: 队列的基本操作! | LeetCode:225. 用队列实现栈
状态:两个队列
可以使用一个队列来完成,由于队列是先进先出,所以可以将队列的先进元素再次压入队列直到最后压入的元素变为第一个元素
//两个队列的pop
//利用一个队列存储除开最后一个元素的所有值,pop后再重新放回
int cu = qIn.size();
while(cu>1)
{
qOut.push(qIn.front());
qIn.pop();
cu--;
}
int res = qIn.front();
qIn.pop();
//现在入队为空,将出队的再压入
int cu2 = qOut.size();
while(cu2)
{
qIn.push(qOut.front());
qOut.pop();
cu2--;
}
return res;
//一个队列,将队列先进元素重新压入当前队列
int cu = qIn.size();
while(cu>1)
{
qIn.push(qIn.front());
qIn.pop();
cu--;
}
int res = qIn.front();
qIn.pop();
return res;